I have a piece of powershell which launches a background job which contains a file watcher- the main script continues to start an exe and wait for it to finish. While the exe is working, if it touches the watched file, the background job springs to life and does some other processing on that file, then carries on waiting. When the script ends, it stops and removes the background job. My worry is, will this clean up the file watcher correctly? Is there a way I can have the parent script raise an event that the background job waits for and triggers that job to shut down?

I've tried this- Parent script:

    start-job -name "start-esinput-watcher" -FilePath ".\input-watcher.ps1"

    $process= "notepad.exe"

    Start-Process -filepath $process -Wait 

    #Create the new event again so it gets caught by the subscription
    New-Event -SourceIdentifier StartES.Stopping -Sender PowerShell.StartES -MessageData "stop" #| Out-Null

Watcher script:

    try {
        $watcher = New-Object System.IO.FileSystemWatcher
        $watcher.Path = "d:\temp\"
        $watcher.Filter = "somefile.txt"
        $watcher.IncludeSubdirectories = $false
        $watcher.EnableRaisingEvents = $true

        $action = { 
            Add-Content d:\temp\input-watcher.log "$([DateTime]::Now.ToString()) es_input.cfg file change detected"

    catch {
        Add-Content d:\temp\input-watcher.log "$([DateTime]::Now.ToString()) Error $($_.Exception.Message)"

    Register-ObjectEvent $watcher Changed -Action $action -SourceIdentifier "ESINPUTCFG_WATCHER"

    while ($true) { 

        $lastEv = get-event | where { $_.SourceIdentifier -eq "StartES.Stopping" } | Select -Last 1

        if ($lastEv -eq $null) {
            Start-Sleep 1 
        else {

    Add-Content d:\temp\input-watcher.log "$([DateTime]::Now.ToString()) Unregistering events and watcher"

    Unregister-Event -SourceIdentifier "ESINPUTCFG_WATCHER"

    Add-Content d:\temp\input-watcher.log "$([DateTime]::Now.ToString()) Fin"

The script never seems to end, logging anything after the while loop. I did have (in the watcher script) an Register-EngineEvent with an action to set a global var to $Global:shouldRun = $false and used that for the while loop, but this also seemed to do nothing. What am I missing?

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.