Search code examples
powershellvariablesinvoke-command

How to pass PowerShell variables from remote to local session


Is there a way with PowerShell to pass multiple variables from a single Invoke-Command remote session back to the local session?

Example (variables are not passed to local session here):

Invoke-Command -ComputerName Server1 -ScriptBlock {
$a = "Variable 1"
$b = "Variable 2"
$c = "Variable 3"
}

Write-Output $a $b $c

Solution

  • $output = Invoke-Command -ComputerName Server1 -ScriptBlock {
        $a = "Variable 1"
        $b = "Variable 2"
        $c = "Variable 3"
        return $a,$b,$c
    }
    

    so, to get some output, you need to produce some output, alternatively you can just do:

    $a,$b,$c = Invoke-Command -ComputerName Server1 -ScriptBlock {
        $a = "Variable 1"
        $b = "Variable 2"
        $c = "Variable 3"
        $a,$b,$c
    }