PowerShell for Windows Admins

Aug 30 2019   10:39AM GMT

Foreach-Object -parallel

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

The introduction of Foreach-Object -parallel in PowerShell v7 preview 3 brings some much needed parallelisation options back into PowerShell.

PowerShell workflows are available in Windows PowerShell but are quirky (to be kind) and can be difficult to use. Workflows were removed in PowerShell v6.0

In PowerShell v7 preview 3 Foreach-Object receives a –parallel parameter that takes a scriptblock as its value.

As a simple example consider this simple counting example from the PowerShell team blog:

PS> (Measure-Command -Expression {1..50 | ForEach-Object {Start-Sleep -Milliseconds 100}}).TotalSeconds
5.4960846

Now using the parallel option

PS> (Measure-Command -Expression {1..50 | ForEach-Object -Parallel {Start-Sleep -Milliseconds 100}}).TotalSeconds
2.2523929

The time to execute is significantly reduced.

A few caveats are needed.

Firstly, the parallel option is an experimental feature so must be enabled

Enable-ExperimentalFeature -Name PSForEachObjectParallel

Secondly, not all tasks are suitable candidates for parallel execution. Expect more discussion on this topic in the near future including contributions on the PowerShell team blog.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: