Log In

Implement multi-threading with .NET runspaces in Powershell

There are multiple options on how to implement multi-threading in Powershell. They are all well known to engineers:

Powershell Jobs

Powershell Workflows

But there is another one, which is not quite popular (because of it's complexity), but very powerfull: .NET runspaces. While it's quite difficult to implement, it don't have main disadvantage of native Powershell ways - we will not spawn tons of powershell.exe processes. All work will be done within a single process and that will highly increase overall script performance.

I will not tell you about theory (mainly because I don't clearly understand details), but will give you some insights and script templates to start moving.

What I know - is that runspace is the single space to invoke some code, while runspacepool - is the pool for the multiple runspaces and .NET knows how to aumatically manage them.

So, let's start.

initialSessionState will hold typeDatas and functions that will be passed to every runspace.

In last three strings we're adding our function to the initialSessionState. Ok, maybe you like object-oriented approach as I do, then here's how you'll define your TypeData and add it to session state: