0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Monitor File Changes Easily

Use the System.IO.FileSystemWatcher class in PowerShell to monitor file changes by creating a watcher object, setting its path and filters, and registering event handlers with Register-ObjectEvent.
📋

Examples

InputMonitor changes in C:\Temp folder
OutputFile created: example.txt File changed: example.txt File deleted: example.txt
InputMonitor changes in D:\Projects with filter *.log
OutputFile created: error.log File changed: error.log File deleted: error.log
InputMonitor changes in empty folder
OutputNo output until a file is created, changed, or deleted
🧠

How to Think About It

To monitor file changes, you create a watcher object that looks at a folder and listens for events like file creation, modification, or deletion. You then tell PowerShell what to do when these events happen by attaching event handlers. This way, the script runs continuously and reacts immediately when a file changes.
📐

Algorithm

1
Create a FileSystemWatcher object
2
Set the folder path and file filter to watch
3
Enable event raising on the watcher
4
Register event handlers for Created, Changed, Deleted events
5
Keep the script running to listen for events
6
Unregister events and dispose watcher when done
💻

Code

powershell
Add-Type -AssemblyName System.IO.FileSystemWatcher
$folder = 'C:\Temp'
$filter = '*.*'
$watcher = New-Object System.IO.FileSystemWatcher $folder, $filter
$watcher.EnableRaisingEvents = $true

Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
    Write-Host "File created: $($Event.SourceEventArgs.Name)"
}
Register-ObjectEvent $watcher Changed -SourceIdentifier FileChanged -Action {
    Write-Host "File changed: $($Event.SourceEventArgs.Name)"
}
Register-ObjectEvent $watcher Deleted -SourceIdentifier FileDeleted -Action {
    Write-Host "File deleted: $($Event.SourceEventArgs.Name)"
}

Write-Host "Monitoring changes in $folder. Press Enter to exit."
[Console]::ReadLine() | Out-Null

Unregister-Event -SourceIdentifier FileCreated
Unregister-Event -SourceIdentifier FileChanged
Unregister-Event -SourceIdentifier FileDeleted
$watcher.Dispose()
Output
Monitoring changes in C:\Temp. Press Enter to exit.
🔍

Dry Run

Let's trace monitoring a file creation event in C:\Temp through the code

1

Create watcher

Watcher set to monitor C:\Temp for all files (*.*)

2

Enable events

Watcher starts listening for Created, Changed, Deleted events

3

File created event

User creates 'test.txt' in C:\Temp, event triggers, script prints 'File created: test.txt'

StepEventFile NameOutput
1Start-Monitoring changes in C:\Temp. Press Enter to exit.
2Createdtest.txtFile created: test.txt
💡

Why This Works

Step 1: FileSystemWatcher object

The FileSystemWatcher object watches a folder for file changes and raises events when something happens.

Step 2: Registering events

Using Register-ObjectEvent, we tell PowerShell what to do when files are created, changed, or deleted.

Step 3: Keeping script alive

The script waits for user input to keep running so it can keep listening for file changes.

🔄

Alternative Approaches

Polling with Get-ChildItem
powershell
while ($true) {
  $files = Get-ChildItem -Path 'C:\Temp'
  # Compare with previous list to detect changes
  Start-Sleep -Seconds 5
}
Simple but inefficient; checks folder repeatedly instead of reacting instantly.
Using WMI events
powershell
Register-WmiEvent -Class Win32_DirectoryChangeEvent -SourceIdentifier DirChange -Action {
  Write-Host "Directory changed"
} -MessageData 'C:\Temp'
Uses Windows Management Instrumentation but is more complex and less flexible.

Complexity: O(1) per event time, O(1) space

Time Complexity

The watcher reacts to events instantly without scanning the whole folder, so time per event is constant.

Space Complexity

Uses minimal memory to store watcher and event handlers; no large data structures needed.

Which Approach is Fastest?

FileSystemWatcher is faster and more efficient than polling because it uses OS notifications.

ApproachTimeSpaceBest For
FileSystemWatcherO(1) per eventO(1)Real-time monitoring with low resource use
Polling with Get-ChildItemO(n) per checkO(n)Simple scripts where real-time is not critical
WMI EventsO(1) per eventO(1)Advanced monitoring with system integration
💡
Always dispose the FileSystemWatcher object and unregister events to free resources.
⚠️
Forgetting to keep the script running causes the watcher to stop immediately.