Prevent duplicate or hanging Powershell processes that run from the Task Scheduler

Many automated processes we write in Powershell are scheduled on a server somewhere and run periodically.
Sometimes, the script may hang. In my experience, the task scheduler setting “Stop the task if it runs longer than:” rarely works properly when a Powershell script hangs. It either thinks it stopped the task, or is unable to.

This can result in memory hogging runaway Powershell processes, locked log files, concurrent user issues, etc etc.

If you want to prevent that from happening, add this function to your script and call it once at the start of your script. It will kill any Powershell process with the same script name that does not match the running process’s Process ID. It requires Powershell 3+:


function preventDoubleSchedule{
    try{
        $scriptFileName = split-path $MyInvocation.PSCommandPath -Leaf
    }catch{$scriptFileName = $Null}
    try{
        [Array]$psProcesses = @(Get-WmiObject Win32_Process -Filter "name like '%Powershell.exe%' and handle != '$pid'" | where {$_})
    }catch{
        Throw
    }
    if($psProcesses.Count -gt 0){
        foreach($psProcess in $psProcesses){
            if($psProcess.CommandLine -like "*$scriptFileName*" -and $scriptFileName){
                ##we've found a Powershell process that is running this script, but does not have the same process ID, lets try to kill it
                try{
                    Stop-Process -Id $psProcess.Handle -Force -Confirm:$False
                }catch{
                    Throw
                }
            }
        }
    }
}

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments