PowerShell

PowerShell: Waiting for jobs to complete with Wait-Job

The cmdlet Wait-Job waits until one or all of the PowerShell jobs running in the session are in a terminating state. In this blog post I will show you an example you can build on. Let’s get started.

Start-Job creates one or more PowerShell background jobs. These jobs are running hidden in the background and enable you to continue your work in PowerShell. This example starts a port scan background job.

Start-Job -Name PortScan -ScriptBlock {Test-NetConnection 192.168.0.150 -Port 88}
Get-Job -Name PortScan

To display the results of this job, run Receive-Job. Note that you can display the result only once! Unless you use the -Keep parameter.

Receive-Job -Name PortScan -Keep | Select-Object RemoteAddress,PingSucceeded,TcpTestSucceeded

Waits until one or all of the PowerShell jobs running in the session are in a terminating state.

Microsoft describes it this way:

The Wait-Job cmdlet waits for a job to be in a terminating state before continuing execution. The terminating states are:

  • Completed
  • Failed
  • Stopped
  • Suspended
  • Disconnected

You can wait until a specified job, or all jobs are in a terminating state. You can also set a maximum wait time for the job using the Timeout parameter, or use the Force parameter to wait for a job in the Suspended or Disconnected states.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/wait-job?view=powershell-7.3

Here is an example of how 2 jobs are created. Waiting for the second job, which takes a very long time. Both jobs are not related, but are good for testing. Finally, the second job is called, but only when the first job has been completed.

Get-Job | Remove-Job -Force

Start-Job -Name PortScan -ScriptBlock {Test-NetConnection 192.168.0.150 -Port 88}
Start-Job -Name Files -ScriptBlock {Get-ChildItem C:\Windows -File -Recurse}
Wait-Job -Name Files
Receive-Job -Name PortScan -Keep | Select-Object RemoteAddress,PingSucceeded,TcpTestSucceeded

Hope this was helpful and you are now enable to implement the Wait-Job cmdlet in your PowerShell scripts.

Categories: PowerShell

Tagged as: ,

2 replies »

Leave a comment

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