Multithreading In Powershell Version 2.0

Starting with version 2.0, Windows Powershell has a set of cmdlets that allow scriptblocks to be run asynchronously. The interface it gives is in some ways similar to what I did in Library-AsyncRunspace.ps1, but different in many other ways. This is likely due to different interpretations of complexity theory. One notable difference is that my script library allowed for runspaces to be initialized and used with more than one scriptblock, while the jobs in Powershell v2.0 cmdlets seem to use one time use runspaces.

The examples for background jobs in Powershell v2.0 are pretty simple. To start a job use start-job.

$job = start-job { ps }

It returns an object that identifies the job. Objects can be piped into the start-job cmdlet and that input will be made available to the job. We then can get the results using the receive-job cmdlet.

Receive-Job $job

Receive-Job will return all results up to that point in time and return. To get all results we must first wait for the scriptblock to finish processing using the wait-job cmdlet.

Wait-Job $job

You can also wait on multiple jobs.

Wait-Job $job1, $job2

Job identifiers are saved and can be retrieved using the get-job cmdlet.

get-job

The result is a list of all parent job identifiers. (Read the about pages for info about parent and child jobs.) Specific jobs can be recalled by their id number or name.

get-job 1, 3, 5
get-job MyFirstJob, MySecondJob

Jobs can be listed by state.

get-job -State Running

You can cancel a job by using the stop-job cmdlet

stop-job $job

The Remove-Job cmdlet will force powershell to forget about past jobs. The line here removes all jobs that have completed.

Remove-Job -State Completed

Or to remove only completed jobs where all output data has been read.

Get-Job -State Completed | where {$_.HasMoreData -eq $false} | Remove-Job

See about_jobs for more info.

Advertisements

~ by lunaticexperimentalist on December 5, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: