On this page

PowerShell Parallel Execution: Complete Guide

Updated on June 25, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

PowerShell 7.0 introduced a game-changing feature for the ForEach-Object cmdlet: the -Parallel parameter. This addition allows administrators to run loop iterations simultaneously rather than sequentially, dramatically reducing execution time for I/O-bound and compute-intensive workloads. Before this, PowerShell offered parallelism through runspaces—lightweight threads within the same process—and job-based approaches like Start-Job and Start-ThreadJob. Understanding when and how to use each method is essential for writing high-performance automation scripts.


Understanding Parallel Execution in PowerShell​

Traditional PowerShell loops process items sequentially, one after another. For loops with few items, this is perfectly adequate. However, when each iteration involves waiting for network responses, file operations, or remote commands, the cumulative time grows linearly with the number of items.

Parallel execution addresses this by running multiple iterations concurrently. PowerShell 7's ForEach-Object -Parallel uses runspaces—separate threads within the same process—to execute code in parallel. These runspaces have significantly less overhead compared to PowerShell jobs or remoting.

Key Insight: Parallel execution does not guarantee improved performance. The overhead of creating and managing threads can outweigh the benefits for simple operations. Parallelism shines when each iteration involves significant waiting time—such as network requests, file I/O, or remote command execution.


ForEach-Object -Parallel (PowerShell 7+)​

The -Parallel parameter transforms the standard ForEach-Object loop into a concurrent execution engine.

Basic Syntax​


1..10 | ForEach-Object -Parallel {

    "Processing item $_ on thread $([System.Threading.Thread]::CurrentThread.ManagedThreadId)"

}

Code explanation: The -Parallel parameter runs the script block concurrently for each item in the pipeline. Each iteration executes in a separate thread. The $([System.Threading.Thread]::CurrentThread.ManagedThreadId) shows which thread is processing each item, demonstrating that multiple threads are used simultaneously.

Controlling Concurrency with ThrottleLimit​

The ThrottleLimit parameter controls how many threads run concurrently. The default limit is 5 threads. When the number of iterations exceeds the throttle limit, additional iterations queue and wait for a thread to become available.


1..50 | ForEach-Object -Parallel {

    $_ * 2

} -ThrottleLimit 10

Code explanation: This processes 50 items with a maximum of 10 concurrent threads. Items beyond the first 10 queue and execute as threads become available. Setting ThrottleLimit too high can overwhelm system resources.

Using $using: for Variable Access​

Inside a parallel script block, variables from the parent scope are not automatically available. Use the $using: scope modifier to reference them:


$commonPath = "C:\Logs"

$servers = Get-Content "servers.txt"



$servers | ForEach-Object -Parallel {

    $server = $_

    $path = $using:commonPath

    Test-Path "\\$server\$path"

}

Code explanation: $using:commonPath brings the local variable $commonPath into each parallel thread. Without $using:, the script block cannot access variables defined outside its scope.

Running as a Background Job​

The -AsJob parameter runs the parallel operation as a PowerShell job:


$job = 1..20 | ForEach-Object -Parallel {

    Start-Sleep -Seconds 1

    $_

} -AsJob



# Do other work while the job runs...



$results = Receive-Job -Job $job -Wait -AutoRemoveJob

Code explanation: -AsJob returns a job object immediately. The script continues executing while the parallel loop runs in the background. Receive-Job -Wait blocks until the job completes and retrieves the results.

Runspace Pool Reuse (PowerShell 7.1+)​

Starting with PowerShell 7.1, ForEach-Object -Parallel reuses runspaces from a runspace pool by default. The ThrottleLimit parameter sets the pool size. This reuse reduces overhead significantly compared to creating a new runspace for each iteration.

To create a new runspace for each iteration instead of reusing from the pool, use the -UseNewRunspace switch.


Runspaces (Windows PowerShell and PowerShell 7)​

Runspaces provide the most flexible and high-performance parallel execution model. They are available in all PowerShell versions and offer lower overhead than PowerShell jobs. ForEach-Object -Parallel and Start-ThreadJob both use runspaces internally.

Creating a Runspace Pool​

A runspace pool manages a set of reusable runspaces, similar to a thread 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)

}



$pool.Dispose()

Code explanation: CreateRunspacePool(1, 10) creates a pool with a minimum of 1 and maximum of 10 runspaces. Each powershell instance is assigned to the pool. BeginInvoke() starts execution asynchronously. AsyncWaitHandle.WaitOne() blocks until each task completes. EndInvoke() retrieves the results. Always call Dispose() to release resources.

Passing Variables to Runspaces​

Variables must be explicitly passed to runspaces using AddArgument() or AddParameter():


$pool = [runspacefactory]::CreateRunspacePool(1, 5)

$pool.Open()



$commonPath = "C:\Logs"

$servers = @("Server01", "Server02", "Server03")



$tasks = foreach ($server in $servers) {

    $ps = [powershell]::Create()

    $ps.RunspacePool = $pool

    $ps.AddScript({

        param($srv, $path)

        Test-Path "\\$srv\$path"

    }).AddArgument($server).AddArgument($commonPath)

    $ps.BeginInvoke()

}



# ... wait for completion and retrieve results ...

$pool.Dispose()

Code explanation: The AddScript() method accepts a script block with parameters. AddArgument() passes values positionally. Each runspace receives its own copy of the arguments, ensuring thread safety.


Start-ThreadJob (PowerShell 7+)​

Start-ThreadJob provides a simpler alternative to raw runspaces. It is available in PowerShell 7 and higher, and can be installed for Windows PowerShell 5.1 from the PowerShell Gallery.


$jobs = foreach ($item in 1..20) {

    Start-ThreadJob -ScriptBlock {

        param($i)

        Start-Sleep -Milliseconds 500

        "Processed $i"

    } -ArgumentList $item

}



$results = $jobs | Receive-Job -Wait -AutoRemoveJob

Code explanation: Start-ThreadJob creates thread-based jobs that are lighter-weight than Start-Job. Unlike Start-Job, which creates a separate process for each job, Start-ThreadJob uses runspaces within the same process, avoiding cross-process serialization overhead.


Comparison of Parallel Execution Methods​

MethodAvailabilityOverheadEase of UseBest ForForEach-Object -ParallelPowerShell 7+LowVery EasyPipeline-based parallel loopsStart-ThreadJobPowerShell 7+ (installable for 5.1)LowEasySimple parallel jobsRunspacesAll versionsLowestComplexMaximum performance, custom logicStart-JobAll versionsHighEasyBackground tasks (not recommended for parallelism)WorkflowsWindows PowerShell 5.1 onlyHighModerateLegacy systems only

Performance Comparison​

In benchmark tests, Start-ThreadJob and ForEach-Object -Parallel both use runspaces and perform similarly. Raw runspaces offer the lowest overhead but require more code.

Start-Job is significantly slower because each job runs in a separate process with its own PowerShell instance. The serialization and deserialization required for cross-process communication also limits the usefulness of returned objects.

Choosing the Right Approach​

Use ForEach-Object -Parallel when:

Use runspaces when:

Use Start-ThreadJob when:

Avoid Start-Job for parallelism:


Best Practices​

Set Appropriate Throttle Limits​

The default throttle limit of 5 is conservative. For compute-intensive tasks on multi-core processors, increasing the limit can improve performance. For I/O-bound tasks, higher limits can hide latency. However, setting the limit too high can overwhelm system resources. Test and measure to find the optimal value.

Avoid Shared State​

Runspaces execute concurrently and do not share state by default. Sharing state requires synchronization primitives like [System.Threading.Mutex] or [System.Threading.ReaderWriterLockSlim]. When possible, design parallel workloads to be independent.

Import Modules Inside the Script Block​

Modules must be imported within each parallel script block, not outside:


$servers | ForEach-Object -Parallel {

    Import-Module ActiveDirectory

    Get-ADComputer -Identity $_

}

Code explanation: Modules are not automatically inherited by parallel threads. Each thread must import its own modules.

Measure Performance Before and After​

Parallelism introduces overhead. Always measure execution time to verify that parallelization provides a net benefit. Use Measure-Command to compare sequential and parallel versions.


Summary​

PowerShell offers multiple approaches to parallel execution, each suited to different scenarios:

Understanding when and how to use each method is essential for building high-performance automation that scales across large datasets and distributed environments.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Using .NET Classes Directly

Next

Enterprise-Grade PowerShell