Download Attune CE

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.

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 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!