Using "Using:" On Remote PowerShell Sessions

by Jul 3, 2013

When you use PowerShell Remoting to execute scripts and commands on another machine, you may have run into an issue like this:

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

Invoke-Command -ScriptBlock { Get-WmiObject -Class $class } -ComputerName $ComputerName 

Once you run this code, you get back this error message:

Apparently, the variable $class is empty on the remote side – which is entirely correct when you think about it. The variable $class exists on your own machine, but not on the remote machine where the script code executes.

In PowerShell 3.0, in order to use local variables on the remote side, prepend them with "using:" like this:

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

Invoke-Command -ScriptBlock { Get-WmiObject -Class $using:class } -ComputerName $ComputerName

Now all is fine!

Twitter This Tip! ReTweet this Tip!