Eli*_*eth 4 powershell file-watcher
我想用powershell观看一个文件夹,我是PS初学者.
当我启动脚本时,该脚本可以运行一次.
但是当我因为更改了一些脚本代码而不得不重新启动脚本时,我收到以下错误消息:
Cannot subscribe to the specified event. A subscriber with the source identifier 'FileChanged' already exists.
Run Code Online (Sandbox Code Playgroud)
我试过了:
这在脚本的顶部:
Unregister-Event -SourceIdentifier FileChanged
Run Code Online (Sandbox Code Playgroud)
不起作用.
如何正确取消注册事件,以便我可以按照我想要的方式运行脚本并处理先前注册的事件?
码
$folder = "C:\temp"
$Watcher = New-Object IO.FileSystemWatcher $folder -Property @{
IncludeSubdirectories = $true
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
$onChanged = Register-ObjectEvent $Watcher Changed -SourceIdentifier FileChanged -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
Write-Host $path
#Move-Item $path -Destination $destination -Force -Verbose
}
Run Code Online (Sandbox Code Playgroud)
小智 5
好的,看看你想要实现什么...回答你的原始问题,你需要做以下事情来取消注册事件.
Get-EventSubscriber -SourceIdentifier "filechanged" | Unregister-Event
Run Code Online (Sandbox Code Playgroud)
我不得不问你为什么要对代码进行1000次调整.如果您尝试注册要监视的1000个不同事件,则使用++修饰符循环和增加变量更有意义.
我已经实现了这一点,如果这是你想要完成的事情,并且可以在需要时分享一些代码.
| 归档时间: |
|
| 查看次数: |
4172 次 |
| 最近记录: |