Note: Running PowerShell v3
I\'ve got a directory setup that is currently:
\\ftproot\\001\\converted
\\ftproot\\001\\inbound
\\ftproot\\001\\pdf
\\f
Is it possible to create an array or list or similar of IO.FileSystemWatcher?
Yes. Making use of a pipeline would be something like:
$fsws = $directoriesOfInterest | ? { Test-Path -Path $_ } | % {
new-object IO.FileSystemWatcher …
}
and $fsws
will be an array, if there is more than one watcher created (it will be a waster if there is only one, $null
if there are none). To always get an array put the pipeline in @(…)
:
$fsws = @($directoriesOfInterest | ? { Test-Path -Path $_ } | % {
new-object IO.FileSystemWatcher …
})
if so, how can I code the Register-ObjectEvent for each instance?
Put the object registration in the same loop, and return both the watcher and the event registration:
$result = @($directoriesOfInterest | ? { Test-Path -Path $_ } | % {
# $_ may have a different value in code in inner pipelines, so give it a
# different name.
$dir = $_;
$fsw = new-object IO.FileSystemWatcher $dir, …;
$oc = Register-ObjectEvent $fsw Created …;
new-object PSObject -props @{ Watcher = $fsw; OnCreated = $oc };
})
and $result
will be an array of objects will those two properties.
Note the -Action
code passed to Register-ObjectEvent
can reference $fsw
and $dir
and thus know which watcher has fired its event.