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.

  1. new-object system.io.filesystemwatcher
  2. 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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -