PowerShell Basics: Enabling Auto Notification Of Specific File Changes

Recently I was asked…

 

“How do I send an email automatically whenever a change is made to a specific file?”

 

There are many 3rd party solutions to achieve this. I however wanted to take the opportunity to learn of a way to complete this task via PowerShell.  Setting up a file watcher seemed to address the issue and its was actually simple to script.

 

The following was created to watch the intended file for changes:

 

 $watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'C:\temp\' 
$watcher.Filter = 'test1.txt' 
$watcher.EnableRaisingEvents = $true
 
$changed = Register-ObjectEvent 
   $watcher 'Changed' -Action {
write-output "Changed: $($eventArgs.FullPath)"
}

Creating the file watcher took the utilization of the FileSystemWatcher object. This script specifically watches the entire directory and path for changes. An added filer is added to specify the required file.

 

Next an ObjectEvent is registered to perform an action the watcher detects a change event. This script highlights a simple output however it could easily modified to enable sending of an email or performing some other task.

 

Removing the ObjectEvent is just as easy and can be performed using the following script:

 Unregister-Event $changed.Id