Unregister a registered filewatcher event does not work

大城市里の小女人 提交于 2019-12-07 10:58:44

问题


I want to watch a folder with powershell and I am a PS beginner.

That script works ONE time when I start the script.

But when I have to restart the script again because I changed some script code I get this error message:

Cannot subscribe to the specified event. A subscriber with the source identifier 'FileChanged' already exists.

I tried:

this at the top of the script:

Unregister-Event -SourceIdentifier FileChanged

does not work.

How do I correctly unregister the event so I can run my script as often I want and the previously registered event is disposed?

CODE

$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
}

回答1:


Ok, looking at what your trying to achieve... to answer your original question, you need to do the following to unregistered the event.

Get-EventSubscriber -SourceIdentifier "filechanged" | Unregister-Event

I have to ask why are you having to make 1000 adjustments to the code. If you are trying to register 1000 different events to be monitored it would make more sense to loop and increment a variable using the ++ modifier.

I have achieved this already if this is what your tying to accomplish and can share some code if you need it.



来源:https://stackoverflow.com/questions/33033901/unregister-a-registered-filewatcher-event-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!