2014-09-26 91 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