Wait Job - PowerShell


Overview

Wait-Job is a PowerShell command that suspends execution of the current script until a specified job completes. This is useful for monitoring the progress of background tasks and ensuring their completion before proceeding with further actions in the script.

Syntax

Wait-Job [-Job] <JobObjectId[]> [-Timeout <TimeSpan>] [-UseSuddenDeath] [-Wait] [<CommonParameters>]

Options/Flags

  • -Job: Specifies the job(s) to wait for. Can accept multiple job objects.
  • -Timeout: Sets a maximum wait time. If the job doesn’t complete within this period, the command times out and returns.
  • -UseSuddenDeath: Terminates child jobs when the parent job completes. This can be useful for ensuring all tasks are completed when the script ends.
  • -Wait: Suspends execution until all specified jobs complete, even without a timeout. This is useful for synchronous execution.

Examples

Simple Job Waiting:

$job = Start-Job { Get-ChildItem }
Wait-Job -Job $job

Waiting with Timeout and Sudden Death:

$job = Start-Job { Get-ChildItem }
Wait-Job -Job $job -Timeout 120 -UseSuddenDeath

Synchronous Job Waiting:

$jobs = Start-Job { Get-ChildItem } -ArgumentList "MyFolder1", "MyFolder2"
Wait-Job -Job $jobs -Wait

Common Issues

  • Job Not Found: Ensure the specified job object actually exists. Use Get-Job to verify the job ID.
  • Timeout Error: Adjust the timeout period to allow sufficient time for the job to complete.
  • Sudden Death Not Working: Make sure the job(s) are child jobs started using Start-Job -Child.

Integration

Combining with Get-Job:

Get-Job | Wait-Job

Using in a Script:

# Start a job
$job = Start-Job { Get-ChildItem "MyFolder" }

# Wait for the job to complete
Wait-Job -Job $job

# Proceed with further actions using the results of the job
$results = Receive-Job $job
  • Start-Job: Creates and starts a new job.
  • Receive-Job: Retrieves the results of a completed job.
  • Get-Job: Retrieves information about existing jobs.