17. December 2008
Andy Schneider
PowerShell Sessions are what are used to connect to remote computers using PowerShell. There are a bunch of new Cmdlets that use the noun PSSession. One big change from CTP2 to CTP3 is that we are now using PSSessions rather than Runspaces. I think this is great, as most of the ops/admin folks I work with don’t have a clue what a runspace is or why they would need one to connect to a remote computer. Session seems to be a much better noun. I think its right on par with a telnet session or an RDP session. This makes a lot sense from an Admin’s point of view.
Anyway, the way we use PSSessions is through the invoke-command Cmdlet. At a very basic level, invoke-command takes two parameters, a ComputerName and a scriptblock to execute on that remote computer as shown in the example below
1: PS C:> invoke-command -computer win7andys -scriptblock {cat env:computername}
2: win7andys
3: PS C:>
I came across a situation where I needed a variable (lets call it $a) that I was using in my local PSSession to be available in my remote PSSession. Let’s try this and see what happens.
1: PS C:> "Hello $a"
2: Hello Foo
3: PS C:> invoke-command -computer win7andys -scriptblock {"Hello $a"}
4: Hello
Notice that $a was there locally but not when we tried to use it remotely in our scriptblock.
Lucky for us, there is a –ArgumentList parameter that we can use with invoke-command. This looks promising.
1: PS C:> invoke-command -computer win7andys -ArgumentList $a -scriptblock {"Hello $a"}
2: Hello
3: PS C:>
Still no dice, but we are close. Turns out we need to declare $a as a parameter in our scriptblock.
1: PS C:> invoke-command -computer win7andys -Argu $a -scriptblock {param ($a) "Hello $a"}
2: Hello Foo
3: PS C:>
And now we have it!