Keeping track of file changes and automating actions is essential for system administrators. This can include managing configurations, monitoring log files, or reloading an application when a file is updated. PowerShell, a powerful scripting tool for Windows, makes this process simple.
In this guide, I’ll show you how to use PowerShell to monitor file changes and restart an application when a file is modified.

There are many reasons why you might want to monitor a file and restart an application automatically:
With PowerShell’s built-in tools, you can handle this easily.
Let me walk you through the process step by step.
To get this done, we’ll use the FileSystemWatcher class from .NET, which is available in PowerShell. This class helps us monitor files or folders for changes and take action when something happens. It can track changes like file edits, new file creations, deletions, and renaming.
We’ll also use PowerShell’s Start-Process and Stop-Process cmdlets to manage restarting the application when needed.
Let me show you how it works.
Here are the key tools we’ll use to set this up:
System.IO.FileSystemWatcher: This is the main .NET class that tracks changes in the file system.Register-ObjectEvent: This PowerShell cmdlet lets us set up an event to run a specific action whenever a file change is detected.Start-Process: Used to launch an application or process.Stop-Process: Used to stop a running application or process using its process ID.With these, we can efficiently monitor file changes and restart an application when needed.
Here’s a simple PowerShell script to watch a specific file for changes and restart an application when the file is updated.
Step-by-Step PowerShell Script:
# Set the file and application details
$FileToMonitor = "C:\Path\To\Your\File.txt" # Full path of the file to monitor
$ApplicationPath = "C:\Path\To\Your\Application.exe" # Path to the application executable
$Filter = "File.txt" # Filter to specify the file name; use "*" for all files
# Initialise the FileSystemWatcher
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = Split-Path $FileToMonitor -Parent
$watcher.Filter = $Filter
$watcher.NotifyFilter = [System.IO.NotifyFilters]'LastWrite' # Watch for content changes
# Define the action to take when a file change is detected
$Action = {
Write-Host "Change detected in $($Event.SourceEventArgs.FullPath) at $(Get-Date)" -ForegroundColor Yellow
# Stop the application if it is running.
$process = Get-Process | Where-Object { $_.Path -eq $ApplicationPath } -ErrorAction SilentlyContinue
if ($process) {
Write-Host "Stopping application: $ApplicationPath" -ForegroundColor Red
Stop-Process -Id $process.Id -Force
}
# Restart the application
Write-Host "Restarting application: $ApplicationPath" -ForegroundColor Green
Start-Process -FilePath $ApplicationPath
}
# Register the event to trigger the action on file change
Register-ObjectEvent -InputObject $watcher -EventName "Changed" -Action $Action
Write-Host "Monitoring file changes on '$FileToMonitor'..." -ForegroundColor Cyan.
Write-Host "Press [Enter] to stop the script."
# Keep the script running to monitor changes
try {
while ($true) {
Start-Sleep -Seconds 1
}
}
finally {
# Cleanup when the script is stopped
Unregister-Event -SourceIdentifier "FileChangeWatcher"
$watcher.Dispose()
Write-Host "Monitoring stopped."
}Variable Setup:
$FileToMonitor: The complete path of the file you want to track for changes.$ApplicationPath: The location of the application that will restart when a change is detected.$Filter: You can specify the exact file name or use * to monitor all files in the folder.File System Watcher Setup:
System.IO.FileSystemWatcher is used to monitor file changes. We set the path to the file’s directory and use NotifyFilter to focus on tracking changes to the file’s content (LastWrite).Action on change:
Stop-Process.Start-Process.Continuous Monitoring
while ($true) loop to continuously monitor file changes. You can stop the script by pressing Enter or Ctrl+C.Cleanup
$FileToMonitor and $ApplicationPath variables with the correct paths for your system.MonitorAndRestart.ps1. Open PowerShell and run the script with .\MonitorAndRestart.ps1.This script can be used in many scenarios:
Monitor Multiple Files:
You can set the Filter to * to monitor all files in the directory or use an array of specific file names to track certain files.
Add Logging:
For better traceability, you can log events to a file using Out-File or Add-Content to record file changes and application restarts.
Monitor More Events:
If you want to monitor additional events like file creations, deletions, or renames, you can adjust the NotifyFilter to include these actions.
$watcher.NotifyFilter = [System.IO.NotifyFilters]'FileName, LastWrite, Size'Error Handling:
You can wrap sections of the script in try and catch blocks to handle unexpected errors gracefully, such as issues with the file or application.
Using PowerShell to monitor files or folders for changes in real-time is an easy but very powerful mechanism. It allows you to potentially take other appropriate action, such as restarting the application, logging the changes, sending messages whenever a file is created, changed, or deleted, or in many cases, a combination of the three. This not only enables your team to potentially respond faster to critical changes, but it also offloads some of the manual work, whenever possible.
You can definitely configure the script to be able to monitor one file, more than one file, files in a folder, or an entire folder. The FileSystemWatcher object that is built into PowerShell has properties that allow you to specify which path you want to monitor, and also has filtering for file types (.txt, .config, .log, etc) so that only the changes you care about are monitored.
Yes, not only can you monitor file changes, but the script can find file creation events, file deletion events, and file rename events. This gives this tool the ability to be used in a variety of scenarios, such as monitoring log files or monitoring critical configuration files.
Yes. Once started, the script can run indefinitely until the PowerShell session or host process is stopped. This can be run as a scheduled task or background job to make it run automatically with no user intervention.
It is safe to run in production if reasonable testing has been done. PowerShell itself is safe to use; the ownership and safety lie with the design of your script and error handling. For mission-critical situations, ensure logging, exception handling, and resource management are set. It is highly suggested that it be run in a test environment before being put into production.
Monitoring file changes and restarting applications based on those changes is a valuable for system administrators and developers. PowerShell makes this process simple and flexible through the FileSystemWatcher class.
By using the provided script, you can automate file monitoring, improving system efficiency and ensuring applications always run with the most up-to-date configurations or data
Comments