I’m trying to use this code to monitor multiple folders for changes.
[xml]$XmlDocument = Get-Content -Path C:\port\syncs.xml
foreach ($sync in $XmlDocument.syncs.sync)
{
Write-host $sync.path
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $sync.path
$FileSystemWatcher.IncludeSubdirectories = $true
$FileSystemWatcher.EnableRaisingEvents = $true
Register-ObjectEvent -InputObject $FileSystemWatcher -SourceIdentifier Monitoring1 -EventName Created -Action {
<#
$Object = "{0} was {1} at {2}" -f $Event.SourceEventArgs.FullPath,
$Event.SourceEventArgs.ChangeType,
$Event.TimeGenerated
Write-Host $Object -ForegroundColor Green
#>
}
}
Hwever, when I run it it throws
Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber with the
source identifier 'Monitoring1' already exists.
Now, I think I have a solid understanding of what’s going on. The SourceIdentifier argument passed to Register-ObjectEvent is treated as a unique identifier and PS refuses to make any more ObjectEvents with the same SourceIdentifier. My question is, how can I avoid this problem without leaving lots of “gartbage” around? For example, I can simply put an iterator in the For loop but that might leave me with an increasing number of useless events when I restart the script. Or I could set SourceIdentifier equal to sync.path but that would cause the same “collision” issue as before.
I guess I need some way to check if the ObjectEvent already exists before I create it, and I need to delete it if it does. Any hints?
Thanks so much
Joe