Waiting for Processes to Exit

by Dec 15, 2016

Sometimes, a PowerShell script needs to wait for external processes to finish. Here is what some users do:

$processNameToWaitForExit = 'notepad'
do
{
    Start-Sleep -Seconds 1
} while (Get-Process -Name $processNameToWaitForExit -ErrorAction SilentlyContinue)

This approach is not ideal though because it waits at least for one second, even if the process is no longer running. Here is a better way:

$processNameToWaitForExit = 'notepad'
Wait-Process -Name $processNameToWaitForExit -ErrorAction SilentlyContinue

Not only is the code shorter. Wait-Process also supports a timeout that you can use to cancel the wait if it takes too long.

Twitter This Tip! ReTweet this Tip!