Using Background Jobs to Speed Up Things

by Mar 13, 2012

PowerShell is single-threaded and can only do one thing at a time, but by using background jobs, you can spawn multiple PowerShell instances and work simultaneously. Then, you can synchronize them to continue when they all are done:

# starting different jobs (parallel processing)
$job1 = Start-Job { Dir $env:windir *.log -Recurse -ea 0 }
$job2 = Start-Job { Start-Sleep -Seconds 10 }
$job3 = Start-Job { Get-WmiObject Win32_Service }

# synchronizing all jobs, waiting for all to be done
Wait-Job $job1, $job2, $job3

# receiving all results
Receive-Job $job1, $job2, $job3

# cleanup
Remove-Job $job1, $job2, $job3

This can speed up logon scripts and other tasks as long as the jobs you send to the background jobs are independent of each other – and take considerable processing time. If your tasks only take a couple of seconds, then sending them to background jobs causes more delay than benefit.

Twitter This Tip! ReTweet this Tip!