How To Monitor A Folder For Any Changes in PowerShell

There might be a lot of tools out there that you can use to monitor a specific folder for any changes. But if it can be done in PowerShell, it could make things easier and more flexible. You can do all sorts of things when a change is being made to the folder, such as send an email notification or write an entry to log the change to the event log, etc.

To make it happen, we will need help from a Windows .Net class called FileSystemWatcher in System.IO namespace.

The following code, when running, monitors the ID folder and will print the newly changed document before writing an entry to a log file when it detects any changes to the folder.

$log = "$home\Desktop\Log.txt"
$pathtomonitor = "X:\ID"
$timeout = 1000

try {
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher $pathtomonitor
$FileSystemWatcher.IncludeSubdirectories = $true

Write-Host "Monitoring content of $PathToMonitor"
while ($true) {
  $change = $FileSystemWatcher.WaitForChanged('All', $timeout)
  if ($change.TimedOut -eq $false)
  {
      # get information about the changes detected
      Write-Host "Change detected:"
      # invoke some actions here when change detected
      if (!($change.ChangeType -eq 'Deleted')){
          Start-Process $change.name -WorkingDirectory $pathtomonitor -verb PrintTo '\\printerserver\printer1' -PassThru | %{ sleep 10;$_ } | kill
      }
      $change | Out-Default
      (Get-Date).ToString() + ", " + $change.ChangeType.ToString() + ", " + $change.Name | Out-File $log -Append
   }
  else
  {
      Write-Host "." -NoNewline
  }
 }
}
finally{
  $FileSystemWatcher.Dispose()
  Write-Host "My Watcher is done."
}

The monitor happens in an endless loop so to abord the monitoring process, you will have to press ctrl+c to break it. And because of that, you will need the try…finally {} to clean up the mess. When ctrl+c occurs, the code in finally{} will be executed, in which the FileSystemWatcher object can be properly disposed of.

The drawback of this approach is that it monitors folder synchronously so if multiple changes are made simultaneously, only the first one will be recorded. If you don’t anticipate multiple changes to the folder, this would be perfect. But if not, check this one out.

2 thoughts on “How To Monitor A Folder For Any Changes in PowerShell

  1. This is sweet and works! Can I run this in a task scheduler or something? When I try, it runs and then stops…so I dont think it keeps the powershell stuff open in the background. I need this to always run so if I log off the server it still monitors.

Leave a Reply to Rob McMillen Cancel reply

Your email address will not be published. Required fields are marked *