Instances, event subscriptions, and "garbage collection"

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

Theycallmevirgo,
Welcome to the forum. :wave:t4:

wihtout having experiences with the FileSystemWatcher … I searched for “Powershell filesystemwatcher more than one folder” and found this …

https://social.technet.microsoft.com/Forums/windowsserver/en-US/c36e024e-da67-495b-9294-9abd7227e6ed/use-filesystemwatcher-to-scan-multiple-folders-in-same-time?forum=winserverpowershell

Please read until the end!

This one seemed to work as well

I appreciate the reference, and it definitely answers my questions. However the answers are not optimistic. The module referenced is from 2014, and I definitely expect this to run as a “service” eventually so I guess it’s back to the drawing board.

Hmmm … I don’t know … has this technology changed since then that much that you expect that the module will not do the job? I’d give it a shot anyway. :man_shrugging:t4:

Yeah, I finally ended up finding it on GitHub. The documentation is… less than ideal. I think I’ll just do Python. Especially since it’s portable and I can make an executable :).