Using FileSystemWatcher Asynchronously

by Jun 5, 2019

In the previous tip we looked at the FileSystemWatcher object and how it can monitor folders for changes. To not miss any changes, however, an asynchronous approach is required which looks like this:

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = "$home\Desktop"
$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,

  Write-Host $Object -ForegroundColor Green

In this example, whenever a change event is detected, an event is raised, and the FileSystemWatcher continues to watch. It is PowerShell’s job to respond to this event, and it does this by using an event handler. Event handlers are executed in the background.

To get rid of the background event handler, run this:

Get-EventSubscriber -SourceIdentifier Monitoring1 | Unregister-Event

Note also that each supported change type raises different events. In this example, we focused on the “Created” event which is raised when new files and folders are created. To respond to other change types, add more event handlers. This returns the names of all supported events:

PS C:\> $FileSystemWatcher | Get-Member -MemberType *Event

   TypeName: System.IO.FileSystemWatcher

Name     MemberType Definition                                                                            
----     ---------- ----------                                                                            
Changed  Event      System.IO.FileSystemEventHandler Changed(System.Object, System.IO.FileSystemEventArgs)
Created  Event      System.IO.FileSystemEventHandler Created(System.Object, System.IO.FileSystemEventArgs)
Deleted  Event      System.IO.FileSystemEventHandler Deleted(System.Object, System.IO.FileSystemEventArgs)
Disposed Event      System.EventHandler Disposed(System.Object, System.EventArgs)                         
Error    Event      System.IO.ErrorEventHandler Error(System.Object, System.IO.ErrorEventArgs)            
Renamed  Event      System.IO.RenamedEventHandler Renamed(System.Object, System.IO.RenamedEventArgs) 

Twitter This Tip! ReTweet this Tip!