PowerShell Job Patterns
A job pattern is a small plan for running several background jobs in a controlled way. It starts a few jobs at a time, waits for them, and collects each result in order.
Collect two jobs in order
Start two jobs, wait for each one, then receive each one in order. The results print in the order you collect them.
$first = Start-Job -ScriptBlock { "one" }
$second = Start-Job -ScriptBlock { "two" }
Wait-Job $first | Out-Null
Wait-Job $second | Out-Null
Receive-Job $first
Receive-Job $second
Remove-Job $first
Remove-Job $secondJoin collected results into one line
Save each collected result in a variable first. Then join the variables into a single line.
$first = Start-Job -ScriptBlock { "red" }
$second = Start-Job -ScriptBlock { "blue" }
Wait-Job $first | Out-Null
Wait-Job $second | Out-Null
$firstResult = Receive-Job $first
$secondResult = Receive-Job $second
"$firstResult, $secondResult"
Remove-Job $first
Remove-Job $secondRun jobs in small batches
Collect one batch before starting the next batch. This is throttling in its simplest form.
$first = Start-Job -ScriptBlock { "task one" }
$second = Start-Job -ScriptBlock { "task two" }
Wait-Job $first | Out-Null
Wait-Job $second | Out-Null
Receive-Job $first
Receive-Job $second
Remove-Job $first
Remove-Job $second
$third = Start-Job -ScriptBlock { "task three" }
Wait-Job $third | Out-Null
Receive-Job $third
Remove-Job $thirdExample
$first = Start-Job -ScriptBlock { "alpha" }
$second = Start-Job -ScriptBlock { "beta" }
Wait-Job $first | Out-Null
Wait-Job $second | Out-Null
Receive-Job $first
Receive-Job $second
Remove-Job $first
Remove-Job $second
$third = Start-Job -ScriptBlock { "gamma" }
Wait-Job $third | Out-Null
Receive-Job $third
Remove-Job $third
"All jobs collected"Key points
- Job pattern: a plan for starting, waiting for, and collecting several background jobs.
- Batch: a small group of jobs started together and collected before the next group starts.
- Start-Job: starts one background job from a script block.
- Wait-Job: waits until a named job finishes.
- Receive-Job: collects the results of one job at a time, which keeps results in the order you collect them.
In this example, two jobs run as one batch and are collected in order, then a third job runs as the next batch, and a final line confirms every job was collected.
Note
starting a small batch instead of every job at once keeps the work controlled and easy to follow.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
You start three jobs and want the results in the order first, second, third. What do you do?