Powershell monitor multiple directories

狂风中的少年 提交于 2019-12-01 12:10:13

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.

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