Remote computing and PowerShell 2.0 part 2 – Running a Scriptblock on a remote machine

Last week I discussed enabling a connection and running a single command on a remote computer using powershell. In this post I’m going to continue that dialogue by discussing running a scriptblock on a remote computer.

A scriptblock (code surrounded by curly brackets {} ) can be run on a remote machine by using the Invoke-Command cmdlet with the -ComputerName parameter.  Take a look at the following example which uses the Invoke-Command cmdlet to execute a Get-ChildItem command on a remote machine.

PS C:>  invoke-command { get-childitem env:p* } -computername nikki

Notice that I didn’t have to use the Enter-PSSession cmdlet first. That is because Enter-PSSession and Invoke-Command are two distinct ways to remote. The Invoke-Command cmdlet’s first option is -Scriptblock. In the previous example I omitted the -Scriptblock parameter because it’s optional.

You can also run a scriptblock on several machines at once suck as the next example.

PS C:> invoke-command { get-childitem env:co* } -computer nikki, tammy

This example performs the same action as the previous example but this time it executes it to both machines nikki and tammy.

Next time I’ll continue this discussion by showing you how to run a scriptblock as a background job, and creating sessions

Leave a Reply