Understanding Parallel Runspaces in PowerShell

Allowing multiple segments of a code to run concurrently will increase the overall script’s efficiency.

Most of the time when writing scripts, performing tasks in a synchronous manner is usually good enough. After all, it’s working, right? Also, code in the script will usually have dependencies on other parts of the script, which means some parts must finish before others begin. But what if a script just had a bunch of stuff to do that normally takes a long time to run that doesn’t have any dependencies on the rest of the code? In that case, we can introduce a level of multithreading or asynchronous behavior that makes the script performs tasks in parallel.

A common way to perform parallel tasks is to use background jobs. Background jobs is a commonly used feature in PowerShell to perform tasks in parallel but it’s not the only way. Another, faster way, is to use parallel runspaces. In a typical PowerShell session, your console runs in a single runspace. Think of a runspace as a container where everything is stored. Inside of this runspace, code is executed asynchronously. But, PowerShell allows you to create your own runspaces and create as many as you want all at the same time! Being able to invoke multiple runspaces at once gives the scripter the ability to run code inside of each runspace independent of the others.

Read more at MCPMag

Leave a Reply