PowerShell ForEach-Object Parallel
ForEach-Object Parallel is a pipeline step that runs each item at the same time. It suits short independent items, and its results need sorting before they are printed.
Parallel items run together
Each number is multiplied by ten in its own parallel run. Sorting the results gives a fixed order.
$r = 1..5 | ForEach-Object -Parallel { $_ * 10 } | Sort-Object
($r -join ", ")An outside variable reaches each block
The using scope carries a word from outside into every block. Sorting keeps the printed order fixed.
$word = "item"
$r = "a", "b" | ForEach-Object -Parallel { $using:word + "-" + $_ } | Sort-Object
($r -join ", ")A limit keeps the work small
ThrottleLimit sets how many blocks run at once. Here only two run at once, and sorting still fixes the order.
$r = 1..4 | ForEach-Object -Parallel { $_ * 2 } -ThrottleLimit 2 | Sort-Object
($r -join ", ")Example
$prefix = "task"
$r = 1..4 | ForEach-Object -Parallel { $using:prefix + "-" + $_ + " is " + ($_ * 3) } | Sort-Object
($r -join ", ")Key points
- Parallel: work where several items run at the same time.
- Use ForEach-Object with Parallel to run a block once for each pipeline item.
- Use the current item variable inside the block to work on one item at a time.
- Use Sort-Object on the results because parallel order is not fixed.
- Use the using scope to share an outside variable with each parallel block.
In this example, the prefix is shared with each block through the using scope. Each block builds one labelled result. Sorting the labels gives a fixed printed order.
Note
A using variable works in a parallel block here, but it fails in a local Invoke-Command block.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why are parallel results sorted before printing?