cancel
Showing results for 
Search instead for 
Did you mean: 

[PowerShell] Monitor File System Activity

Shinichi_Hayash
Not applicable
Employee

There is a Microsoft .NET Framework class library called  FileSystemWatcher.

This class monitors file related events like Create, Rename, Delete and run any action that you specify.

Following example is FileSystemWatcher notifying when *.DV* files under the C:\EVStorage folder were created or deleted.

20140707_133335_0.jpg

This is how to do it.

  • Create a FileSystemWatcher object using New-Object.
  • Set  $FileWatch.Path property to any folder that you want to monitor .
  • Set $FileWatch.Filter property to *.DV*
  • Set $FileWatch.IncludeSubdirectories and $FileWatch.EnableRaisingEvents to true
  • Finally register as an event so that commands in the –Action part will be fired upon each events
$FileWatch = New-Object System.IO.FileSystemWatcher
$FileWatch.Path = "C:\EVStorage"
$FileWatch.Filter = "*.DV*"
$FileWatch.IncludeSubdirectories = $true
$FileWatch.EnableRaisingEvents = $true
Register-ObjectEvent $FileWatch "Created" -Action { Write-Host -ForegroundColor yellow (get-date -Format "yyyy/MM/dd HH:mm:ss") "[Created]  [$($eventArgs.Name)]"}
Register-ObjectEvent $FileWatch "Deleted" -Action { Write-Host -ForegroundColor red    (get-date -Format "yyyy/MM/dd HH:mm:ss") "[Deleted]  [$($eventArgs.Name)]"}
Register-ObjectEvent $FileWatch "Renamed" -Action { Write-Host -ForegroundColor white  (get-date -Format "yyyy/MM/dd HH:mm:ss") "[Renamed]  [$($eventArgs.Name)]"}

Unfortunately, each event does not contain process information so there is no way to tell which process created or deleted the files.

To understand which process accessed the files, Process Monitor is the tool to use.

FileSystemWatcher class can be used as a “light” real time monitoring tool to see if any archived files are created.

Use cases are..

  • Understand archiving rate from the file creation time. Keep in mind that FilySystemWatcher has a InternalBufferSize of 4KB and if it overflows, it can loose track.
  • If you are changing the configuration, FileSystemWatcher will be the first one to notice you that your configuration was valid and archive task actually archived something.