3

Is it possible to modify remote variables? I am trying to do something like the following:

$var1 = ""
$var2 = ""

Invoke-Command -ComputerName Server1 -ScriptBlock{
$using:var1 = "Hello World"
$using:var2 = "Goodbye World"
}

When I try this I get the error:

The assignment expression is not valid.  The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.

So obviously, it doesn't work using this method, but are there any other approaches I could take? I need to use and modify those variables in both a remote and local scope

  • You want the "Hello World" value to be written back to the variables in your local/calling session? – Mathias R. Jessen Mar 18 '20 at 16:15
  • Well looks like he might be running the command on a remote machine and wants the response back into the first machines variables. Is this correct? – ArcSet Mar 18 '20 at 16:58
  • Yes, that is correct, Mathias. And there is more than one variable being edited, which makes just returning a single value from the command a little more complicated. – William Oettmeier Mar 18 '20 at 16:58

2 Answers2

4

So what you are trying to do wont work. But here is a work around.

Place your data you want returned into a hashtable and then capture the results and enumerate over them and place the value into the variables.

$var1 = ""
$var2 = ""

$Reponse = Invoke-Command -ComputerName Server1 -ScriptBlock{
    $Stuff1 = "Hey"
    $Stuff2 = "There"
    Return @{
        var1 = $Stuff1
        var2 = $Stuff2
    }
}

$Reponse.GetEnumerator() | %{
    Set-Variable $_.Key -Value $_.Value
}

$var1
$var2

This will return

Hey
There
ArcSet
  • 6,518
  • 1
  • 20
  • 34
3

What you're trying to do fundamentally cannot work:

A $using: reference to a variable in the caller's scope in script blocks executed in a different runspace (such as remotely, via Invoke-Command -ComputerName, as in your case):

  • is not a reference to the variable object (to the variable as a whole),

  • but expands to the variable's value, and you fundamentally cannot assign something to a value.

In the case at hand, $using:var1 effectively becomes "" in your script block (the value of $var1 when Invoke-Command is called), and something like "" = "Hello world" cannot work.

The conceptual help topic about_Remote_Variables (now) mentions that (emphasis added):

A variable reference such as $using:var expands to the value of variable $var from the caller's context. You do not get access to the caller's variable object.

See this answer for background information.


As for a potential solution:

Make your script block output the values of interest, then assign to local variables, as shown in ArcSet's helpful answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775