Parallel Execution¶
Parallel execution allows PowerShell to perform multiple operations at the same time, significantly improving performance when processing large datasets or long‑running tasks. PowerShell offers two primary mechanisms for parallelism: ForEach-Object -Parallel (PowerShell 7+) and runspaces (Windows PowerShell and PowerShell 7). Each approach has different strengths and use cases.
1. Parallel Execution with ForEach-Object -Parallel (PowerShell 7+)¶
ForEach-Object -Parallel provides a simple, built‑in way to run script blocks in parallel. It uses PowerShell’s thread pool and requires no additional setup.
Example: processing items in parallel¶
1..10 | ForEach-Object -Parallel {
"Processing item $_ on thread $([System.Threading.Thread]::CurrentThread.ManagedThreadId)"
}
Key parameters¶
ThrottleLimitControls how many parallel threads run at once.
1..50 | ForEach-Object -Parallel {
$_ * 2
} -ThrottleLimit 10
AsJobRuns the parallel operation as a background job.
1..20 | ForEach-Object -Parallel {
Start-Sleep -Seconds 1
$_
} -AsJob
When to use it¶
- PowerShell 7+
- Simple parallel workloads
- Tasks that do not require shared state
- Quick performance improvements without complex code
2. Parallel Execution with Runspaces¶
Runspaces provide a more advanced and efficient parallel execution model. They offer lower overhead than PowerShell jobs and greater control than ForEach-Object -Parallel. Runspaces are ideal for high‑performance automation and large‑scale parallel workloads.
Example: using a runspace pool¶
$pool = [runspacefactory]::CreateRunspacePool(1, 10)
$pool.Open()
$tasks = foreach ($i in 1..10) {
$ps = [powershell]::Create()
$ps.RunspacePool = $pool
$ps.AddScript("Start-Sleep -Milliseconds 200; 'Task $i completed'")
$ps.BeginInvoke()
}
foreach ($task in $tasks) {
$task.AsyncWaitHandle.WaitOne()
$task.PowerShell.EndInvoke($task)
}
Why runspaces are fast¶
- Minimal overhead
- No process creation
- No job infrastructure
- Direct access to .NET threading
When to use runspaces¶
- Windows PowerShell (where
ForEach-Object -Parallelis unavailable) - High‑performance automation
- Large‑scale parallel operations
- Scenarios requiring shared state or custom synchronization
3. Choosing Between ForEach-Object -Parallel and Runspaces¶
| Scenario | Best Option |
|---|---|
| PowerShell 7+ and simple parallel tasks | ForEach-Object -Parallel |
| Windows PowerShell | Runspaces |
| Maximum performance | Runspaces |
| Minimal code complexity | ForEach-Object -Parallel |
| Need shared state or custom threading | Runspaces |
4. Summary¶
Parallel execution is a powerful performance optimization technique in PowerShell. Two primary approaches are available:
-
ForEach-Object -ParallelSimple, built‑in parallelism for PowerShell 7+.
-
Runspaces
High‑performance, flexible threading suitable for complex or large‑scale workloads.
Using parallel execution effectively can dramatically reduce execution time and improve scalability in automation workflows.