0

在下面的代码中,action.bat - 调用一个将文件名作为参数传递的 java 进程,而 log.txt - 记录一行文件名是用时间戳创建的。

我正在通过删除 10 个完美运行的 txt 文件来测试这个脚本,我重复了这个测试几次,log.txt 得到更新,并且 action.bat 也被正确调用。

但是,当我让这个 filewatcher 运行 4 小时并删除 10 个新的文本文件时,只有 log.txt 得到了更新,但 action.bat 文件没有被调用。

当我再次杀死 powershell 并重新启动脚本并使用 10 个新文件再次测试时,它工作正常。

为什么等待 4 小时后开始进程不会被调用?但日志语句在行动中更新

我的代码类似于net event filewatch.ps1

 $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "D:\code\Apps\input"
    $watcher.Filter = "*.txt"
    $watcher.IncludeSubdirectories = $false
    $watcher.EnableRaisingEvents = $true 
### DEFINE ACTIONS AFTER A EVENT IS DETECTED
    $action = {
    $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "D:\code\Apps\log.txt" -value $logline   
                Start-process -Filepath D:\code\Apps\action.bat $path -Wait -passthru; 
                }    

### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY  
    $created = Register-ObjectEvent $watcher "Created" -Action $action
    while ($true) {sleep 10}
4

1 回答 1

0

看起来您缺少Register-ObjectEventCmdLet 上的参数,-SourceIdentifier 'FileCreated'.

更正的代码

 $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "D:\code\Apps\input"
    $watcher.Filter = "*.txt"
    $watcher.IncludeSubdirectories = $false
    $watcher.EnableRaisingEvents = $true 
### DEFINE ACTIONS AFTER A EVENT IS DETECTED
    $action = {
    $path = $Event.SourceEventArgs.FullPath
                $changeType = $Event.SourceEventArgs.ChangeType
                $logline = "$(Get-Date), $changeType, $path"
                Add-content "D:\code\Apps\log.txt" -value $logline   
                Start-process -Filepath D:\code\Apps\action.bat $path -Wait -passthru; 
                }    

### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY  
    $created = Register-ObjectEvent $watcher 'Created' -SourceIdentifier 'FileCreated' -Action $action
    #while ($true) {Start-Sleep 10}
于 2016-05-14T21:15:50.447 回答