Wait-Job

PowerShell Cmdlet Deep Dive: Wait-Job

Welcome back to Wahmans PowerShell Blog! Today, we’re diving into a fundamental yet powerful cmdlet when it comes to managing background jobs in PowerShell — Wait-Job.

What is Wait-Job?

According to Microsoft’s documentation, Wait-Job “waits until one or all of the PowerShell jobs running in the session are in a terminating state.” That means it’s used to pause code execution until background jobs are complete. This is extremely useful when parallelizing tasks or when you need to make sure that all jobs are done before proceeding in your script.

Let’s explore four practical examples from beginner to more advanced usage of Wait-Job.

🧪 Example 1: Basic Wait for a Single Job

Start-Job -ScriptBlock { Start-Sleep -Seconds 5; "Job done." } | Wait-Job

This is the most basic usage. We start a background job that sleeps for 5 seconds. Wait-Job ensures we wait for that job to complete before continuing.

🛠️ Example 2: Wait for Multiple Jobs

$jobs = @()
foreach ($i in 1..3) {
    $jobs += Start-Job -ScriptBlock { Start-Sleep -Seconds 3; "Job completed." }
}

Wait-Job -Job $jobs

Here, we start three background jobs and use Wait-Job with the -Job parameter to wait for all of them to complete before moving on.

🚦 Example 3: Use with Receive-Job to Collect Results After Completion

$job = Start-Job -ScriptBlock { Get-Process | Where-Object { $_.CPU -gt 1 } }
Wait-Job -Job $job
$result = Receive-Job -Job $job
$result

It’s good practice to use Wait-Job before Receive-Job to ensure the job has finished. This approach pulls back the processed data after the job has completed.

🚀 Example 4: Advanced — Use in Workflow with Parallel Execution

$scripts = @("Server01", "Server02", "Server03")
$jobs = foreach ($server in $scripts) {
    Start-Job -ScriptBlock {
        param($srv)
        # Simulate server test action
        Start-Sleep -Seconds (Get-Random -Minimum 2 -Maximum 6)
        "Finished scanning $srv"
    } -ArgumentList $server
}

# Wait for all server scan jobs to finish
Wait-Job -Job $jobs

# Output results
$jobs | ForEach-Object { Receive-Job -Job $_ }

This is a more advanced usage scenario where jobs are started for multiple servers simultaneously. Wait-Job ensures all jobs finish before processing the results.

🔚 Wrapping up

Wait-Job is vital in workflows that involve concurrency and parallelism. It ensures your scripts run smoothly without unexpected behavior due to incomplete background jobs.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *