Chris Umbel

Asynchronous and remote execution with powershell 2 ctp3

An interesting feature released with the PowerShell 2 CTP3 is the ability to run background jobs consisting of arbitrary PowerShell code. In order to use this functionality you must download and install the PowerShell 2 CTP3 and the WinRM (Windows Remote Management) 2.0 CTP.

Keep in mind that installing the CTP requires uninstalling previous versions of PowerShell. Depending on the PowerShell and operating system versions involved the procedure can vary. Google/Bing is your friend.

Once bringing up PowerShell you have to enable remoting by invoking the aptly named Enable-PSRemoting cmdlet

Enable-PSRemoting -force

Now the meat. Consider the following code:

# copy bigfile.txt on a background thread
$job = start-job -scriptBlock { cp bigfile.txt bigfilecopy.txt }

# here's where we'd perform some other logic while our file copies

# wait for job to finish
wait-job $job

Note that you can also retrieve the status of jobs and the return values with the Get-Job and Receive-Job cmdlets respectively.

More interesting still is the ability to execute jobs remotely on other systems running PowerShell and WinRM. This can be demonstrated with the Invoke-Command cmdlet coupled with the -AsJob parameter as follows:

Invoke-Command -ComputerName Comp1, Comp2 -ScriptBlock { cp bigfile.txt bigfilecopy.txt } -AsJob

The -ComputerName parameter's values of Comp1 and Comp2 indicate that our script will will execute on two remote machines named Comp1 and Comp2.

In conclusion PowerShell 2 introduces some interesting features for asynchronous and remote operations. This opens many doors for administrators and developers alike with minimal code.

Tue Jun 30 2009 19:50:15 GMT+0000 (UTC)

Follow Chris
RSS Feed
Twitter
Facebook
CodePlex
github
LinkedIn
Google