Powershell扫描txt文件然后运行命令

时间:2014-03-11 18:50:17

标签: powershell azure

我正在尝试扫描文件夹,当文本文件出现时,它会抓取两行文本并运行命令以关闭文本文件中的azure服务器。我还希望它在读取后删除文本文件。我不确定我是否正确地做了这个,并且我已经拼凑了一些我找到的脚本。目前,它将读取已添加文件但未对信息执行任何操作且未运行关闭。任何帮助将非常感激。

$folder = 'c:\ftptest' # Enter the root path you want to monitor. 
$filter = '*.*'  # You can enter a wildcard filter here. 
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 


# Run Event 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
$name = $Event.SourceEventArgs.Name 
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated
$cloudSvcName,$vmname = Get-Content $name | Out-String
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green 
Out-File -FilePath c:\scripts\logs\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp '$cloudSvcName' '$vmname' "
Stop-AzureVM -servicename $cloudSvcName -name $vmname -force} 

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情。它监视一个文件夹运行powershell,前两行文本作为azure云服务名称和vmname,然后记录它。我在Windows服务器上使用freeSSHd接受从Linux机箱发送到它的sftp。

# watch a file changes in the current directory, 
# execute all tests when a file is changed or renamed

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\ftpsites\centos'
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $false
$watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite -bor [System.IO.NotifyFilters]::FileName

while($TRUE){
    $result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Changed -bor [System.IO.WatcherChangeTypes]::Renamed -bOr [System.IO.WatcherChangeTypes]::Created, 1000);
    if($result.TimedOut){
        continue;
    }
    write-host "Change in " + $result.Name
Start-Sleep -s 1
    $name = $result.Name
    $cloudSvcName,$vmname = Get-Content 'C:\ftpsites\centos\*.txt'
    $date = Get-Date -Format g
    stop-azurevm -servicename $cloudSvcName -name $vmname -force
    del C:\ftpsites\centos\*.txt
    Out-File -FilePath c:\scripts\logs\filewatcher.txt -Append -InputObject "$date $name"
}