对WatcherChangeTypes使用Start-job

时间:2014-09-26 09:46:17

标签: powershell powershell-v2.0 powershell-v3.0

有没有办法监控powershell后台目录中的文件更改。

我试图按照以下方式做。

 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文件的任何信息。虽然如果我不使用start-job,脚本会按预期工作。

2 个答案:

答案 0 :(得分:2)

Start-Job将在新的上下文中启动您的作业,因此工作目录将是默认目录(例如\Users\Username),Get-Location将返回此目录。

解决此问题的一种方法是保存原始工作目录,将其作为参数传递给作业,并使用Set-Location在作业中设置工作目录

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

答案 1 :(得分: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