Search code examples
powershellwildcardfilesystemwatcher

Powershell: FileSystemWatcher monitor only certain subfolders


How can I monitor only certain subfolders of a folder with a FileSystemWatcher in Powershell?

I create a new FileSystemWatcher like so:

$folder = 'path\to\root\monitoring\folder'
$filter = '*.xml'   

$fsw = New-Object IO.FileSystemWatcher

$fsw.Path = $folder
$fsw.Filter = $filter
$fsw.IncludeSubdirectories = $true
$fsw.EnableRaisingEvents = $true

In that root monitoring folder there is a tree-like structure:

task01

  • working
  • approval
  • approved

task02

  • working
  • approval
  • approved

task03

  • working
  • approval
  • approved

I only want to check changes in the "approved" Folders.

The easiest solution would be

$folder = 'path\to\root\monitoring\folder\*\approved'

but that doesn't quite seem to work...


Solution

  • You are going to have to set up a watcher on each directory that you want to monitor as there is no wildcard support for paths (see the Exceptions Section on this link: FileSystemWatcher.Path) Trying to work the Filter property to support a possible wildcard path will not work either.