Monthly Archive

Categories

Foreach-Object -parallel

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.

Comments are closed.