Using FileSystemWatcher Synchronously

by Jun 4, 2019

Here is a chunk of code illustrating how PowerShell can use the FileSystemWatcher to synchronously watch a folder including subfolders for file changes:

$folder = $home 
$filter = '*'  


try
{
    $fsw = New-Object System.IO.FileSystemWatcher $folder, $filter -ErrorAction Stop
}
catch [System.ArgumentException]
{
    Write-Warning "Oops: $_"
    return
}

$fsw.IncludeSubdirectories = $true
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'

do
{
    $result = $fsw.WaitForChanged([System.IO.WatcherChangeTypes]::All, 1000)
    if ($result.TimedOut) { continue }
    
    $result
    Write-Host "Change in $($result.Name) - $($result.ChangeType)"

} while ($true)

This code would monitor your user profile for changes in files to the FileName and LastWrite properties.

A synchronous watcher keeps PowerShell busy, so in order to be able to abort the monitoring, a timeout of 1000ms is set. Every 1000ms, PowerShell returns control to you, and if you don’t press CTRL+C, the loop continues.

Note that a synchronous filesystemwatcher can miss changes: when a file change occurs and WaitForChange() returns, any subsequent change that occurs before WaitForChange() is called again will be missed.

If you don’t want to miss any changes, use an asynchronous approach (see next tip).


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!