Question:
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:
1 2 |
Cannot subscribe to the specified event. A subscriber with the source identifier 'FileChanged' already exists. |
I tried:
this at the top of the script:
1 2 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$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 } |
Answer:
Ok, looking at what your trying to achieve… to answer your original question, you need to do the following to unregistered the event.
1 2 |
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.