Running Powershell in Parallel

Up until now I’ve written most of my Powershell scripts to run sequentially; query one machine, then the next, then the one after. Depending on the task at hand and / or the number of machines this can take a serious amount of time.

Enter parallelism. Jobs, Runspaces etc are concepts that I have been aware of for some time but I had never taken the time to get to grips with them. After recently having to query a mass of machines which took over an hour to complete, I figured it was time to make the change.

After a quick bit of searching I came across a function on Technet Gallery called invoke-async. This seems to take all the hard work out of starting, stopping, retrieving jobs etc. While it may not be the most optimal way of doing things, it sure makes them easy!

The function is called as follows

Where $machines is an array of computer names that will be interrogated, “system” is the variable that will be set and “sb” is the variable holding the scriptblock.

I created a script that to read back the uninstall keys on a machine using WMI to find out what software is installed on a machine. Running it sequentially I found that most machines returned results quickly, some took a second or two and others took a lot longer as they were not available.

Running this with Invoke-Async meant that multiple could be queried at once and any delays in returning results could be tolerated as other machines were being queried at the same time. Running the query like this meant that results were back in under 4 minutes, down from 12 minutes.

Here is my test function. You can use Measure-Command to return the time taken to execute the code. Remember to grab Invoke-Async from Technet Gallery.

Leave a Reply

Your email address will not be published. Required fields are marked *