Register-ObjectEvent cmdlet在Powershell上不能正常工作,但在ISE上工作



我正在制作一个Powershell脚本来监视一个文件夹,当创建一个新项目时,脚本需要将该文件复制到另一个文件夹。

我遇到的问题是,当我在Powershell ISE中执行它时,它可以完美地工作,但在Powershell上执行它时,它只在Powershell窗口打开的时间段内工作(>1秒)。

我试着把sleep命令放在最后,发现只有当脚本结束时才会采取行动,在这种情况下,当我按CTRL+C在Powershell中停止脚本时,应该在我创建项目时采取的行动被一起执行。

不知道我是做错了什么还是误解了什么。

下面是我用来测试它的脚本:

$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.path = "\192.168.5.127dataTestWatcher"
$Destination = "C:TestWatcher"
$Watcher | Get-Member -MemberType Event
$Watcher.EnableRaisingEvents = $true
$action = {
$path = $event.SourceEventArgs.FullPath
$name = $event.SourceEventArgs.Name
$changetype = $event.SourceEventArgs.ChangeType
Write-Host "File $name at path $path was $changetype at $(get-date)"
Copy-Item $Watcher.path $Destination
}
Register-ObjectEvent $Watcher 'Created' -Action $action

任何帮助或建议都将不胜感激。

最诚挚的问候,

Gregor在评论中提供了关键的提示:

To确保脚本无限期地处理事件,您可以在脚本末尾使用Wait-Event调用无限期地等待永远不会到达的事件,它保持脚本运行,但是-与Start-Sleep不同-通过传递给Register-ObjectEvent-Action参数的脚本块阻止事件处理:

$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.path = "\192.168.5.127dataTestWatcher"
$Destination = "C:TestWatcher"
$Watcher.EnableRaisingEvents = $true
$action = {
$path = $event.SourceEventArgs.FullPath
$name = $event.SourceEventArgs.Name
$changetype = $event.SourceEventArgs.ChangeType
Write-Host "File $name at path $path was $changetype at $(get-date)"
Copy-Item $Watcher.path $Destination
}
# Register the event with a self-chosen name passed to -SourceIdentifier
# and an -Action script block.
$null = 
Register-ObjectEvent $Watcher Created -SourceIdentifier FileWatcher -Action $action
# Now wait indefinitely for an event with the same source identifier to arrive.
# NONE will ever arrive, because the events are handled via the -Action script block.
# However, the call will prevent your script from exiting, without
# blocking the processing of events in the -Action script block.
Wait-Event -SourceIdentifier FileWatcher

或者,让do不使用-Action脚本块,并在Wait-Event循环中处理事件。:

$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.path = "\192.168.5.127dataTestWatcher"
$Destination = "C:TestWatcher"
$Watcher.EnableRaisingEvents = $true
# Register the event with a self-chosen name passed to -SourceIdentifier
# but WITHOUT an -Action script block.
$null = Register-ObjectEvent $Watcher 'Created' -SourceIdentifier FileWatcher
# Now use Wait-Event with the chosen source identifier to
# to indefinitely receive and then process the events as they 
# become available.
while ($event = Wait-Event -SourceIdentifier FileWatcher) {
$path = $event.SourceEventArgs.FullPath
$name = $event.SourceEventArgs.Name
$changetype = $event.SourceEventArgs.ChangeType
Write-Host "File $name at path $path was $changetype at $(Get-Date)"
Copy-Item $Watcher.path $Destination
$event | Remove-Event # Note: Events must be manually removed.
}

相关内容

最新更新