Monitor File Changes With PowerShell

60 seconds is a workable polling delay when event watching is not available; for normal local development, a FileSystemWatcher can react to file-system events and restart your app without waiting for the next poll. The reliable pattern is to keep a PowerShell process running, watch only the source files that matter, and call a restart script from the watcher’s event handler. This guide builds that setup for a local .NET app, then shows how to adapt it for other applications and less reliable file locations.

Situation Best Approach What to Watch
Local source code on a development machine FileSystemWatcher event registration The source directory and relevant file extension
Renames, deletes, or file path changes File-name notification filters FileName and DirectoryName
Network share or environment where events are missed Polling loop A snapshot of file names, sizes, and write times
Application installed as a Windows service Watcher plus service restart command Deployment or source directory, not application logs

What File Watching and Restarting Does

PowerShell can use .NET’s System.IO.FileSystemWatcher class to receive notifications when files are created, changed, deleted, or renamed. Unlike a loop that repeatedly scans a directory, the watcher waits for the operating system to report an event.

That notification is not the application restart itself. Your script must supply an event action that runs the restart command. The watcher also needs a PowerShell host that remains alive; if the script exits, there is nothing left to receive events.

A good watcher setup has three parts:

  1. A narrow directory to monitor, usually source code rather than the entire project folder.
  2. A restart script that safely stops the process it started and launches a replacement.
  3. A persistent PowerShell process that registers the watcher events and stays open.

Avoid watching build-output folders such as bin, obj, dependency folders, logs, or application state files. Restarting an app can write files, which can trigger the watcher again and create a restart loop.

How to Automatically Restart an Application After File Changes

The example below watches C# files in a src directory and restarts a .NET project. It keeps the application process ID in a state folder outside the watched source directory.

Step 1: Create the Restart Script

  1. Create a file named restart-app.ps1 in the project’s top-level folder.
  2. Replace WidgetApi.csproj with the name and relative path of your own project file.
  3. Keep the .watcher folder outside the source directory that will be monitored.
$projectPath = Join-Path $PSScriptRoot 'src\WidgetApi.csproj'
$stateDirectory = Join-Path $PSScriptRoot '.watcher'
$pidFile = Join-Path $stateDirectory 'app-process.json'
$stdoutLog = Join-Path $stateDirectory 'app-output.log'
$stderrLog = Join-Path $stateDirectory 'app-error.log'
$restartLog = Join-Path $stateDirectory 'restart.log'
New-Item -ItemType Directory -Path $stateDirectory -Force | Out-Null
if (Test-Path -LiteralPath $pidFile) {
    try {
        $previous = Get-Content -LiteralPath $pidFile -Raw | ConvertFrom-Json
        $oldProcess = Get-Process -Id $previous.Id -ErrorAction SilentlyContinue
        # Confirm this is still the process originally started by this script.
        if (
            $oldProcess -and
            $oldProcess.StartTime.ToUniversalTime().ToString('o') -eq $previous.StartTimeUtc
        ) {
            Stop-Process -Id $oldProcess.Id -Force
            Wait-Process -Id $oldProcess.Id -ErrorAction SilentlyContinue
        }
    }
    catch {
        Write-Warning "Could not read or stop the previously recorded application process."
    }
}
$newProcess = Start-Process `
    -FilePath 'dotnet' `
    -ArgumentList "run --project `"$projectPath`"" `
    -WorkingDirectory $PSScriptRoot `
    -RedirectStandardOutput $stdoutLog `
    -RedirectStandardError $stderrLog `
    -PassThru
@{
    Id           = $newProcess.Id
    StartTimeUtc = $newProcess.StartTime.ToUniversalTime().ToString('o')
} | ConvertTo-Json | Set-Content -LiteralPath $pidFile -Encoding utf8
Add-Content -LiteralPath $restartLog -Value "$(Get-Date -Format o) Restarted application process $($newProcess.Id)"

This script does more than kill the PID listed in a text file. It checks the recorded process start time too, which reduces the risk of stopping an unrelated process if Windows has reused an old PID.

For another type of application, change the Start-Process command:

  • For a Node.js app, start npm.cmd with your project’s start command.
  • For a Python app, start python with the path to your entry-point script.
  • For a custom executable, set -FilePath to the executable and provide its arguments.

Run the restart script once to start the application before enabling the watcher.

powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\restart-app.ps1

The Bypass setting applies only to that PowerShell process. It does not change the machine-wide execution policy.

Step 2: Create the File Watcher Script

  1. Create watch-app.ps1 next to restart-app.ps1.
  2. Set $sourcePath to the directory containing files that should cause a restart.
  3. Change $filter if your application uses a different file type.
$sourcePath = Join-Path $PSScriptRoot 'src'
$filter = '*.cs'
$restartScript = Join-Path $PSScriptRoot 'restart-app.ps1'
if (-not (Test-Path -LiteralPath $sourcePath -PathType Container)) {
    throw "The source directory does not exist: $sourcePath"
}
if (-not (Test-Path -LiteralPath $restartScript -PathType Leaf)) {
    throw "The restart script does not exist: $restartScript"
}
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $sourcePath
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $true
# FileName and DirectoryName cover rename, delete, and path-name events.
# LastWrite and Size cover ordinary file-content saves.
$watcher.NotifyFilter = "FileName,DirectoryName,LastWrite,Size"
$configuration = [pscustomobject]@{
    RestartScript = $restartScript
}
$restartAction = {
    $config = $Event.MessageData
    $changedPath = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType
    Write-Host "Detected $changeType event: $changedPath"
    & $config.RestartScript
}
foreach ($eventName in 'Changed', 'Created', 'Deleted', 'Renamed') {
    Register-ObjectEvent `
        -InputObject $watcher `
        -EventName $eventName `
        -SourceIdentifier "AppWatch.$eventName" `
        -MessageData $configuration `
        -Action $restartAction | Out-Null
}
$watcher.EnableRaisingEvents = $true
Write-Host "Watching $sourcePath for $filter files. Press Ctrl+C to stop."
try {
    while ($true) {
        Wait-Event | Out-Null
    }
}
finally {
    $watcher.EnableRaisingEvents = $false
    Get-EventSubscriber |
        Where-Object SourceIdentifier -like 'AppWatch.*' |
        ForEach-Object {
            Unregister-Event -SubscriptionId $_.SubscriptionId
        }
    Get-Job |
        Where-Object Name -like 'AppWatch.*' |
        Remove-Job -Force -ErrorAction SilentlyContinue
    $watcher.Dispose()
}

Put the restart command in the -Action event handler and keep the PowerShell host running, or the watcher cannot continue to restart the application after the script exits.

The watcher registers an action for each relevant event type. When PowerShell receives an event, the action runs restart-app.ps1, which stops the prior app process and starts a new one.

Step 3: Start the Persistent Monitoring Session

Launch the watcher from the project folder.

powershell.exe -NoExit -NoProfile -ExecutionPolicy Bypass -File .\watch-app.ps1

Use -NoExit to keep the watcher session open. The script also waits for events in a loop, but keeping the console open makes it easier to read event messages and investigate errors after the script stops.

Keep this window open while developing. Press Ctrl+C in that window when you want to stop monitoring and unregister the event subscriptions.

Step 4: Verify That the Restart Works

  1. Confirm that the application starts before making a source change.
  2. Save a matching file, such as a .cs file below src.
  3. Check the watcher window for a detected event.
  4. Check the restart log and application output files in .watcher.
Get-Content -LiteralPath .\.watcher\restart.log

If the application fails after a restart, inspect the captured error output.

Get-Content -LiteralPath .\.watcher\app-error.log

A successful watcher restart means the process ID in .watcher\app-process.json changes after a qualifying source-file event, and the application responds normally through its usual local URL, command-line output, or health check.

Handling Saves, Renames, and Duplicate Events

File-system events are notifications, not a perfect one-to-one record of a person pressing Save. An editor may write a temporary file, replace the original, update metadata, and rename the replacement. That can produce more than one event for one apparent edit.

Start with a narrow watch scope:

  • Watch source files, not the whole repository.
  • Use one watcher per extension when you need several distinct file filters.
  • Keep generated output, logs, PID files, package caches, and temporary files outside the watched directory.

For rename, deletion, or directory-path events, set NotifyFilter = "FileName,DirectoryName". Add LastWrite and Size when ordinary content changes should also restart the app.

A move within one monitored location can appear as a rename event. A move across locations may instead arrive as separate delete and create notifications. If you must associate a delete with a following create as one move, hold the delete information briefly; one implementation uses a timer interval of 500 ms to look for the related creation event. Application restarts usually do not need that association: either event can simply invoke the restart workflow.

Add a path check inside $restartAction when temporary-file names should not trigger a restart. Do not solve that problem by watching every file in the project tree; that normally makes unnecessary restarts worse.

Use a Polling Loop When File Events Are Unreliable

FileSystemWatcher is usually the better choice for a local source directory. Polling is useful when you are watching a network share, a mounted volume, or another location where notifications may be delayed or missed.

The following script compares a snapshot of matching files every 60 seconds. It detects additions, removals, renames, size changes, and write-time changes.

Create a file named poll-watch-app.ps1:

$sourcePath = Join-Path $PSScriptRoot 'src'
$filter = '*.cs'
$restartScript = Join-Path $PSScriptRoot 'restart-app.ps1'
function Get-SourceSnapshot {
    Get-ChildItem -LiteralPath $sourcePath -File -Recurse -Filter $filter |
        ForEach-Object {
            '{0}|{1}|{2}' -f $_.FullName, $_.Length, $_.LastWriteTimeUtc.Ticks
        } |
        Sort-Object
}
$previousSnapshot = Get-SourceSnapshot
Write-Host "Polling $sourcePath for $filter files. Press Ctrl+C to stop."
do {
    Start-Sleep -Seconds 60
    $currentSnapshot = Get-SourceSnapshot
    $difference = Compare-Object `
        -ReferenceObject $previousSnapshot `
        -DifferenceObject $currentSnapshot
    if ($difference) {
        Write-Host "Source change detected. Restarting the application."
        & $restartScript
        $previousSnapshot = $currentSnapshot
    }
}
while ($true)

Start the application once, then run the polling script in a persistent PowerShell session.

powershell.exe -NoExit -NoProfile -ExecutionPolicy Bypass -File .\poll-watch-app.ps1

Polling is less immediate and performs repeated directory scans, but it is easier to reason about when a file provider does not send dependable change events.

Running the Monitor Reliably

For local development, leave the watcher in an open terminal. For an unattended environment, the watcher itself must run under a persistent process-management mechanism; simply launching a .ps1 file once is not enough.

Use these operating rules:

  • Run the watcher under an account that can read the watched directory and start or stop the application.
  • Store watcher state and logs outside the watched source path.
  • Prefer a deployment pipeline or application-native reload mechanism for production deployments.
  • Use polling rather than event notifications if the watched files are on an unreliable remote share.
  • Restart Windows services through the service manager instead of tracking a child-process PID.

For an application already installed as a Windows service, the restart operation can be as simple as this:

Restart-Service -Name 'WidgetApi'

Place that command in the event action or in a restart script invoked by the event action. The monitoring PowerShell process must still remain running after registration.

Frequently Asked Questions

Can PowerShell monitor multiple files at once?

Yes. A watcher monitors a directory and can include subdirectories, while its filter limits which names cause events. Use separate watcher instances when you need different extension filters, or watch a common source directory and reject unwanted paths inside the event action.

Can a watcher detect deleted and renamed files?

Yes. File and directory name events are covered by NotifyFilter = "FileName,DirectoryName". Register Deleted and Renamed handlers in addition to Changed if deleting or moving a source file should restart the application.

Why does my application restart more than once after one save?

A single editor save can produce several file-system events, especially when the editor writes a temporary file and renames it into place. Restrict the watched directory and extension, exclude generated files, and make the restart operation safe to run repeatedly.

Can I restart a Windows service instead of a development process?

Yes. Use Restart-Service -Name 'WidgetApi' in the handler or in the restart script, provided the PowerShell account has permission to control that service. Keep the watcher process alive and monitor only the deployment files that should trigger the service restart.

Should I use event watching or polling?

Use event watching for local source directories because it reacts when Windows reports a change. Use a polling loop with a 60-second delay when the files are on a network share or another location where change notifications are inconsistent; after choosing the method, make one harmless source edit and confirm that the application restarts and its logs remain clean.