How to use Wait-Process in Powershell?


Wait-Process cmdlet in PowerShell is used to wait for the process to stop before the execution moves on to the next step.

Example

We have a snipping tool application running and we need to wait for the process to stop first and then move on to the next step.

PS C:\> Get-Process SnippingTool | Select Name,Id,CPU
Name          Id    CPU
----          --    ---
SnippingTool  7440   2.0625

To wait for the process to stop first we will use the Wait-Process command. You can provide ProcessName or ID.

Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool'
Write-Output 'Snipping tool Process is stopped'

Output

PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop

Once the process is stopped,

PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
Snipping tool Process is stopped

If the desired process can’t stop, the execution waits forever. You can also provide the timeout parameter in seconds so if the process can’t stop in the mentioned time, it will throw an error.

Example

Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool' -Timeout 5
Write-Output 'Snipping tool Process is stopped'

Output

PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
CloseError: (System.Diagnostics.…cess (SnippingTool):Process) [Wait-Process],
TimeoutException
Snipping tool Process is stopped

In such instance we can use the change the ErrorAction setting to Stop.

Example

Write-Output "Waiting for the Process to Stop"
Wait-Process -Name 'SnippingTool' -Timeout 5 -ErrorAction Stop
Write-Output 'Snipping tool Process is stopped'

Output

PS C:\> C:\Temp\TestPS1.ps1
Waiting for the Process to Stop
CloseError: (System.Diagnostics.…cess (SnippingTool):Process) [Wait-Process],
TimeoutException

Updated on: 04-Jan-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements