PowerShell Parallel Results
Parallel results are the values that parallel work returns. Parallel work means work that runs at the same time in separate workers, and this lesson shows how to collect its values in a fixed order.
Collect parallel results in a variable
Run five small jobs in parallel and store what they return. Sorting gives a fixed order.
$results = 1..5 | ForEach-Object -Parallel { $_ * 10 }
($results | Sort-Object) -join ", "Keep submission order with an index
Give each result its input number. Sorting by that number restores submission order.
$indexed = 1..5 | ForEach-Object -Parallel { [ordered]@{Index = $_; Value = $_ * 10} }
($indexed | Sort-Object Index | ForEach-Object { $_.Value }) -join ", "Collect thread job results the same way
Thread jobs also return values. Wait for them, then sort before printing.
$jobs = 1..3 | ForEach-Object { Start-ThreadJob -ScriptBlock { param($n) $n * 10 } -ArgumentList $_ }
($jobs | Receive-Job -Wait | Sort-Object) -join ", "Example
$indexed = 1..4 | ForEach-Object -Parallel { [ordered]@{Index = $_; Value = $_ * $_} }
$ordered = $indexed | Sort-Object Index | ForEach-Object { $_.Value }
($ordered) -join ", "
"count: $($ordered.Count)"Key points
- Parallel result: a value returned by one parallel worker.
- Use ForEach-Object -Parallel to run the same block for each input at the same time.
- Collect results in a variable to keep them for later use.
- Use Sort-Object to put collected results in a fixed order before printing them.
- Use an index value to remember each input's place, then sort by that index.
In this example, four inputs run in parallel and each result carries its input number. Sorting by that number restores submission order, the values print on one line, and the count line confirms that all four results arrived.
Note
Parallel workers finish in any order, so raw parallel output order is not a promise.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
You run 1..5 in parallel and store the results. What do you do before printing them to get a fixed order?