Foreach -parallel (Part 1: PowerShell 7)

by Dec 6, 2019

PowerShell 7 comes with a built-in parameter to run different tasks in parallel. Here is a simple example:

1..100 | ForEach-Object -ThrottleLimit 20 -Parallel { Start-Sleep -Seconds 1 $_ }

In a normal ForEach-Object loop, this would take 100 seconds to execute. Thanks to -parallel, the code is executed in parallel. -ThrottleLimit defines the “chunks”, so in this example, there are 20 threads running in parallel, reducing the total execution time to 5 seconds.

Before you get too enthusiastic, keep in mind that each thread runs in its own PowerShell environment. Fortunately, you can access local variables with the prefix “using:”:

$text = "Output: "

1..100 | ForEach-Object -ThrottleLimit 20 -Parallel { Start-Sleep -Seconds 1 "$using:text $_" }

Once you start using multi-threading, you need to know about thread-safety, though. Complex objects such as ADUser objects may not be shared across multiple threads, so it depends on the individual use case whether or not parallelization will work for you.

While parallel ForEach-Object loops are built-in in PowerShell 7, that does not mean you cannot use parallelization in Windows PowerShell. There are plenty of modules that implement this functionality in Windows PowerShell. We’ll talk about that in an upcoming trick.


 

You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: https://psconf.eu (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: https://psconf.eu/register.html. Help build the agenda and make this “your” event by submitting hypothetical sessions you’d like to hear: https://powershell.one/psconfeu/psconf.eu-2020/reverse-cfp. And if you’d like to present yourself and join the psconf.eu speakers’ team, submit proposals: https://sessionize.com/psconfeu/.

Twitter This Tip! ReTweet this Tip!