2014-09-26 90 views
1

有沒有辦法監視powershell背景中目錄中的文件更改。使用WatcherChangeTypes啓動作業

我試圖按照下面的方法做。

Start-Job { 
    $watcher = New-Object System.IO.FileSystemWatcher 
    $watcher.Path = get-location 
    $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; 
     } 
    Add-Content D:\receiver.txt "file name is $($result.Name)" 
    } 
} 

這不起作用。我沒有收到有關receiver.txt文件的任何信息。儘管如果我不使用開始工作,腳本仍按預期工作。

回答

2

Start-Job將在新的上下文中啓動您的工作,所以工作目錄將成爲默認目錄(例如\Users\Username)並且Get-Location將返回此目錄。

一個對付這種方式保存原始工作目錄,將它傳遞給工作作爲參數,並使用Set-Location設置工作目錄作業

$currentLocation = Get-Location 
Start-Job -ArgumentList $currentLocation { 
    Set-Location $args[0]; 
    ... 
} 
+0

非常感謝!這對我有效。 – 2014-09-28 17:08:22

0

我會使用Register-ObjectEvent並跟蹤每個事件類型。它使用與Start-Job中使用的相同的PSJobs,但適用於監視實際事件並根據您提供的內容運行特定操作。

未測試:

$watcher = New-Object System.IO.FileSystemWatcher 
$watcher.Path = get-location 
$watcher.IncludeSubdirectories = $true 
$watcher.EnableRaisingEvents = $false 
$watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite -bor [System.IO.NotifyFilters]::FileName 
ForEach ($Item in @('Changed','Renamed','Created')) { 
    (Register-ObjectEvent -EventName $Item -InputObject $watcher -Action { 
     #Set up a named mutex so there are no errors accessing an opened file from another process 
     $mtx = New-Object System.Threading.Mutex($false, "FileWatcher") 
     $mtx.WaitOne() 
     Add-Content D:\receiver.txt "file name is $($result.Name)" 
     #Release so other processes can write to file 
     [void]$mtx.ReleaseMutex() 
    }) 
} 

快速的方式來阻止FileSystemWatcher的

Get-EventSubscriber | Unregister-Event 
Get-Job | Remove-Job -Force