3

#PSTip Passing local variables to a remote session in PowerShell 3.0

Note: This tip requires PowerShell 3.0 or above.

Passing local variables to a remote session has become a lot easier in PowerShell 3.0 compared to previous versions. Lets have a look at a few examples. Consider the following variables defined in your local PowerShell session:

$a = "PowerShell"
$b = "Rocks"

If you want to use these variables in a remote session, you will see that the following will not work:

$a = "PowerShell"
$b = "Rocks"

Invoke-Command -ComputerName Server01 -ScriptBlock {
   Write-Output &quot;The value of </code>$a is: $a&quot;
   Write-Output &quot;The value of <code>$b is: $b&quot;
}

The value of $a is:
The value of $b is:

In PowerShell 2.0 we had two options in order to pass our local variables to the remote session. The first option was to pass on the variables to the –ArgumentList parameter. We then had to pick them up from the $args array, and keep track of the order we passed the variables in. For example, the first variable specified on the –ArgumentList parameter could be picked up accessing $args[0], the second variable accessing $args[1], and so on. As we can see in the following example:

Invoke-Command -ComputerName Server01 -ScriptBlock {
   Write-Output &quot;The value of </code>$a is: $($args[0])&quot;
   Write-Output &quot;The value of <code>$b is: $($args[1])&quot;
} -ArgumentList $a,$b

The value of $a is: PowerShell
The value of $b is: Rocks

The second option was to use the –ArgumentList parameter and a param block:

Invoke-Command -ComputerName Server01 -ScriptBlock {
   param ($first,$second)

   Write-Output &quot;The value of </code>$a is: $first&quot;
   Write-Output &quot;The value of <code>$b is: $second&quot;
} -ArgumentList $a,$b

The value of $a is: PowerShell
The value of $b is: Rocks

In PowerShell 3.0 we can simply use the Using scope modifier followed by a colon and the name of the local variable we want to reference:

Invoke-Command -ComputerName Server01 -ScriptBlock {
   Write-Output &quot;The value of </code>$a is: $using:a&quot;
   Write-Output &quot;The value of `$b is: $using:b&quot;
}

The value of $a is: PowerShell
The value of $b is: Rocks
Filed in: Columns, Tips and Tricks Tags: , , , ,

3 Responses to "#PSTip Passing local variables to a remote session in PowerShell 3.0"

  1. Hank Stallings says:

    I am running a script block that brings back the variable information I need to the screen, but can I capture that in a variable to be used for another command?

  2. Alex Verboon says:

    Hi Jan, many thanks for this, just what i needed.

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.