Using "Using:" On Remote PowerShell Sessions (Part 2)

by Jul 9, 2013

In a previous tip we talked about using PowerShell Remoting to execute code on a remote machine, and how to use "using:" to carry over local variables to the remotely executed script.

However, this only works in PowerShell 3.0. If you must still use PowerShell 2.0, you can use a different technique:

$class = 'Win32_LogicalDisk'
$ComputerName = 'storage1'

Invoke-Command -ScriptBlock { param($class) Get-WmiObject -Class $class } -ComputerName $ComputerName -ArgumentList $class 

In this example, the local variable was turned into an argument and received on the remote side using a param() statement. In order to carry over local variables to remote sessions, submit the local variables to -ArgumentList and receive them in your remote code through param().

Note that this approach supports positional parameters only, so you must submit multiple values in the order in which they are received by param().

Twitter This Tip! ReTweet this Tip!