Executing with Timeout

by Aug 26, 2015

Start-Process can start processes but does not support a timeout. If you wanted to kill a runaway process after a given timeout, you could use an approach like this:

#requires -Version 2

$maximumRuntimeSeconds = 3

$process = Start-Process -FilePath powershell.exe -ArgumentList '-Command Start-Sleep -Seconds 4' -PassThru

try
{
    $process | Wait-Process -Timeout $maximumRuntimeSeconds -ErrorAction Stop
    Write-Warning -Message 'Process successfully completed within timeout.'
}
catch
{
    Write-Warning -Message 'Process exceeded timeout, will be killed now.'
    $process | Stop-Process -Force
}

Wait-Process is used to wait for the process. If it did not end within the specified timeout, Wait-Process raises an exception. Your error handler can then decide what do to.

In the example, the catch block would kill the process.

Note that the example process in this sample is a second PowerShell instance, basically executing a Start-Sleep command to simulate some long running task. If you change the Start-Sleep parameter to less than the number of seconds specified in $maximumRuntimeSeconds, then the process will complete within the timeout, and your script would not try and kill it.

Twitter This Tip! ReTweet this Tip!