Monitoring Folder Content

by Sep 7, 2011

You can use a FileSystemWatcher object to monitor a folder and write a log for all newly created files. For example, this can be used as an "Inbox" for incoming job requests.

$log = "$env:temp\newfiles.txt"
$folder = $home
$timeout = 1000

$FileSystemWatcher = New-object System.IO.FileSystemWatcher $home

Write-Host "Press any key to abort monitoring $home"
do {
 
  $result = $FileSystemWatcher.WaitForChanged("created", $timeout)
  
 if ($result.TimedOut -eq $false) { 
    '{0} : {1}' -f (Get-Date), $result.Name | 
      Out-File $log -Append  
    Write-Warning ("Detected new file: " + $result.name)
  }

} until ( [System.Console]::KeyAvailable )

Write-Host "Monitoring aborted."
Invoke-Item $log

Twitter This Tip!
ReTweet this Tip!