How to Monitor a Folder for Changes the Easy Way

0

Monitoring a folder for any changes could be very useful. You can set it up so that when anything added or deleted in the folder you can be notified by an email or an entry can be added in a log file so you can have a history of what’s happened. The problem is, Windows doesn’t have this monitoring feature available out of the box. So, how can we approach this in a way that is easy and without buying any software?

Windows .NET framework has a class called FileSystemWatcher in System.IO NameSpace that has been around for years. If you are a programmer, you probably can craft up a little app using this class fairly easily. But if not, here is a PowerShell way that you can approach as well.

The following code, when running, monitors H:\Temp folder and writes an entry when any types of changes are detected.

$log = "$home\Desktop\Log.txt"
$pathtomonitor = "H:\temp"
$timeout = 1000

$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:"
$change | Out-Default
(Get-Date), $change.ChangeType.ToString(), $change.Name | Out-File $log -Append
}
else
{
Write-Host "." -NoNewline
}
}
image 8 600x251 - How to Monitor a Folder for Changes the Easy Way

Obviously, it’s not ideal and has some flaws in it. For example, if I delete multiple files at once, only the first one is detected. That’s because this code runs sequentially. when a change is detected, it starts the processing procedure and misses the second change that occurs right after.

Here is a better example at Idera that takes the same route but uses an asynchronous approach that keeps the monitoring and processing running concurrently so when one change happens it doesn’t stop the monitoring. It uses a queue internally so when there are many changes in a very short period of time, all of them will be lined up in the queue and will be processed once PowerShell is no longer busy.

/Update on Feb. 4, 2019/

Jose F. Roniello has created a PowerShell module called pswatch to simplify the whole process. The module has been made available in PowerShell Gallery so you can’t use Import-Module directly. But here is how you can import, thanks to 4Sysops.

iex ((new-object net.webclient).DownloadString("http://bit.ly/Install-PsWatch")) 
Import-Module pswatch
image 5 600x222 - How to Monitor a Folder for Changes the Easy Way

LEAVE A REPLY

Please enter your comment!
Please enter your name here