Search code examples
powershellpowershell-remoting

Modifying remote variables inside ScriptBlock using Invoke-Command


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


Solution

  • 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