A pedant that hangs out in the dark corner-cases of the web.

Thursday, January 05, 2012

PowerShell Wait-DirectoryChange FileSystemWatcher function

Here's a handy way to watch for changes in a directory using the FileSystemWatcher in PowerShell.

function Wait-DirectoryChange
Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.
.Parameter Directory
The directory to monitor, in standard or Universal Naming Convention (UNC) notation. Default is current directory.
.Parameter ChangeType
The type of change to watch for: Created, Deleted, Changed, Renamed, or All. Default is All.
.Parameter Include
The type of files to watch. For example, "*.txt" watches for changes to all text files. Default is all files.
.Parameter Timeout
The time to wait before timing out. Default is forever.
[CmdletBinding()] Param
[string][ValidateScript({Test-Path $_ -PathType Container})] $Directory = $PWD.ProviderPath,
[IO.WatcherChangeTypes] $ChangeType = 'All',
[string] $Include,
[TimeSpan] $Timeout = 0
$watcher =
if($Include) { New-Object IO.FileSystemWatcher $Directory,$Include }
else { New-Object IO.FileSystemWatcher $Directory }
if($Timeout.TotalMilliseconds) { $watcher.WaitForChanged( $ChangeType, $Timeout.TotalMilliseconds ) }
else { $watcher.WaitForChanged( $ChangeType ) }
nal wdir Wait-DirectoryChange

No comments: