Using Local Variables Remotely

by Oct 25, 2012

If you want to send a script block to a remote computer, it is important to understand that the script block is evaluated on the remote computer. So all local variables are null:

PS> $Path = 'C:\test'
PS> $scriptblock = { "Variable Path is $Path" }
PS> & $scriptblock
Variable Path is C:\test
PS> Invoke-Command -Scriptblock $scriptblock -ComputerName storage1
Variable Path is

In PowerShell v3, you can prefix a local variable with "using:" so that it will get transferred to the remote machine:

PS> $Path = 'C:\test'
PS> $scriptblock = { "Variable Path is $using:Path" }
PS> Invoke-Command -Scriptblock $scriptblock -ComputerName storage1
Variable Path is C:\test

Note that the prefix "using" is allowed only in script blocks that are executed by Invoke-Command and sent to a remote machine or with InlineScript inside a workflow.

Twitter This Tip! ReTweet this Tip!