c# - Powershell - Globally register IO.FileSystemWatcher -
i've created filesystemwatcher (c# object). run code below in powershell session.
# filters $filter = "somefile.txt" $flagfolder = "c:\path\to\some\folder" # instantiate watcher $watcher = new-object io.filesystemwatcher $flagfolder, $filter -property @{ includesubdirectories = $false notifyfilter = [io.notifyfilters]'filename, lastwrite' } # event: $filter created $oncreated = register-objectevent $watcher created -sourceidentifier filecreated -action { $path = $event.sourceeventargs.fullpath $name = $event.sourceeventargs.name $changetype = $event.sourceeventargs.changetype $timestamp = $event.timegenerated write-host "the file '$name' $changetype @ $timestamp" write-host $path someglobalfunction $param }
after running code above, if get-job
reports filewatcher:
id name psjobtypename state hasmoredata location -- ---- ------------- ----- ----------- -------- 74 filecreated notstarted false
but, if open new powershell session , get-job
reports nothing....
i need fire whenever anybody or anything creates file $pathfolder\somefile.txt
... works when session defines $watcher
creates file.
you need 2 things make work.
new-object system.io.filesystemwatcher
register-objectevent
i think minimum code need make filesystemwatcher work.
set filesystemwatcher object
$w = new-object system.io.filesystemwatcher $w.path = $pwd
$pwd
(current working directory) automatic variable.
subscribe "created" event (for simplicity)
register-objectevent -inputobject $w -eventname created -sourceidentifier "file.created" ` -action {write-host -object "a file created" -foregroundcolor green -backgroundcolor black}
now, if create file in current working directory, powershell write "a file created" screen. doesn't matter how file gets created--in current session, in different powershell session, through file explorer, using cmd.exe--doesn't matter.
this answer has more elaborate code. simplified code here based directly on it.
Comments
Post a Comment