Download AttuneOps LogoAttuneOps CE for free Automate your system admin tasks

Download
  • Automated OS Installation
  • Virtual Host APIs
  • Centralised Scheduler
  • Script Automation
  • Document Generation
  • Rapid Automation Development
  • Portable Blueprint

How to Automate File Monitoring and Application Restarts with PowerShell

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.

Automate File Monitoring and Application Restarts with PowerShell

Why Monitor Files and Restart Applications?

There are many reasons why you might want to monitor a file and restart an application automatically:

  • Updating Configuration Files: If a configuration file is changed, restarting the application can apply the new settings right away.
  • Monitoring Log Files: For systems that process logs, restarting may be needed after a log rotation or when the file becomes too large.
  • Improving Efficiency: Restarting an application after a file change ensures it always runs with the latest information.

With PowerShell’s built-in tools, you can handle this easily.

Let me walk you through the process step by step.

Tools and Concepts

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.

Key PowerShell Cmdlets and Concepts:

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.

PowerShell Script: File Monitoring and Application Restarts

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."
}

Script Overview:

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:

  • When the file is modified, the script checks if the application is running. If it is, it stops the process with Stop-Process.
  • Then, it restarts the application using Start-Process.

Continuous Monitoring

  • The script uses a while ($true) loop to continuously monitor file changes. You can stop the script by pressing Enter or Ctrl+C.

Cleanup

  • The script makes sure that resources are properly cleaned up and events are unregistered when the monitoring is stopped.

Running the Script

  • Edit the Script: Replace the $FileToMonitor and $ApplicationPath variables with the correct paths for your system.
  • Execute the Script: Save the script as MonitorAndRestart.ps1. Open PowerShell and run the script with .\MonitorAndRestart.ps1.
  • Stopping the Script: To stop the script, press Enter or Ctrl+C in the PowerShell window.

Use Cases for This Script

This script can be used in many scenarios:

  • Configuration Management: Automatically restart an application or service when its configuration file is updated.
  • Log File Monitoring: Monitor log files and restart the associated application or process when the log file is rotated or modified.
  • Dynamic Application Behaviour: Restart applications when files like templates, resources, or external data files are changed.

Optional Enhancements

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.

Automate File Monitoring and Application Restarts with PowerShell: Frequently Asked Questions

What advantages are there to using PowerShell for monitoring files?

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.

Can I run this script to monitor more than one file/folder?

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.

Can I monitor other events besides just file events?

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.

Can this script run in the background indefinitely?

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.

Is this script safe to run in production?

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.

Final Thoughts

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

Post Written by
Shivam Mahajan
Shivam Mahajan
Shivam Mahajan is an editor skilled in SysOps, Tech, and Cloud. With experience at AttuneOps and other companies, he simplifies complex technical material for easy understanding.

Comments

Join the discussion!