Multi-Threading Super-Fast Disk Utilization Report using Background Jobs in PowerShell

Automate task using script is always helpful, it reduced human error and efforts, but sometimes it still takes a lots of time to execute same command on multiple remote servers one by one. For example, my disk utilization script, it works perfectly fine, but taking lots of time to generate report for thousands of servers. To get the result faster I started looking for using Background Jobs, and the result was really promising.

Earlier approx. for 500 servers, it took almost 10 to 15 seconds each and total more than 2 hours, and after using PS Background Jobs, it takes less than 5 minute to generate the report.

This is what I did with my script,

Now the script will check for input file containing list of the servers and it will create jobs for every server till it reach the predefined max thread count (20 in my case), and will wait till the running job count reduced, and add jobs again. This loop will continue till jobs created for all the servers. Once all jobs created, it will wait till the status of the jobs changed from ‘running’ state to something else. Once all jobs completed it will collect the job out-put and merge them all and generate the report.

Note: While creating Jobs, make sure you use max thread, in this script each jobs took 30-35 MB memory, so you have to make sure that you have sufficient resource your jobs.

Once you execute the script, it will start adding the jobs with a progress report.

As soon as running job count reached to max thread count, it will wait till it get reduced again

Once reduced, it will start adding jobs again.

One all jobs created, it will wait till all jobs finished, and then it will generate the report.

You can get the report on console if you running the script from ISE by typing $Result.

I hope this script will help to understand how to create background jobs. Happy Scripting J

Disclaimer: All posts and opinions on this site are provided AS IS with no warranties. These are our own personal opinions and do not represent our employer’s view in any way.

This article currently have 6,257 views

Follow me

CC BY-ND 4.0 This work is licensed under a Creative Commons Attribution-NoDerivatives 4.0 International License.

One comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.