Powershell – Use Version 2 to work faster! Background Jobs

Powershell

One of the COOLEST features that came in version 2 of Powershell was the ability to run jobs in the background.   This is incredibly important because normally in old “Classic” Powershell with a large “FOREACH” loop each task would run and would go on to the next task only when the previous one was done.  

So if at one point you hit a big snag, things would slow right down until that “snag” finished it’s work.

But not with background jobs.

SUPER easy to work with too!

So here we have job that will waste a LOT of time.

foreach ( $i in 1..50) {

get-childitem c: –recurse

}

 

It is a completely pointless script in that is just get’s a directory of Drive C.  (Well not just a directory, EVERYTHING in fact).  That will waste a lot of time.  And the next time it goes to run, it CAN’T until it finishes the FIRST time!

But this could also be a task that sometimes is busy, and sometimes get’s done quick.   But they’re tied to the same rules.  It’s a big line up of things in a queue.

But enter Background Jobs!  Life get’s amazingly over the top better.  With Background Jobs everything get’s queued up and runs in parallel.  So although one job might be very busy, the other jobs can at least get a shot and doing their work.  You’re still limited to CPU and Processing power but at least you’re no longer limited to the RUN, WAIT, RUN, WAIT, RUN, WAIT game.

Now you’re running them all and the Big jobs will still process while the little ones can go through.

This same script could be run like this using START-JOB

foreach ( $i in 1..50) {

start-job { get-childitem c: –recurse }

}

You’ll note when you run it this way all 50 “Get-Childitems” are running at once.  (which will max out your CPU) but they are all working at once.

If you want to check on the status of the background jobs just run a GET-JOB CmdLet.  You can even just list jobs that are in process.  You can use STOP-JOB to pause various jobs to balance CPU time if needed or REMOVE-JOB to get them out of the QUEUE.

There’s also RETURN-JOB that would give you the normal piped output of that job to do something with it once it’s done.

 

But it’s beautiful to work with and easy to use.  And a free benefit of using Powershell V2.

One word

Sweeeeeeeet!

Sean
The Energized Tech

Leave a Reply