1

I start a PowerShell script that calls a function with Invoke-Command on another computer. I want to declare a variable that is available over all this sessions.

$var = "global"

function do-function{
    $var = "function"
    return $var
}

$var
invoke-command -ComputerName NameOfComputer -scriptblock  ${function:do-function}
$var

output:

global
function
global

My target is to get:

global
function
function
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
MaxW
  • 49
  • 3
  • 10

1 Answers1

0

You have to assign the return value from the Invoke-Command cmdlet to the variable:

$var = "global"

function do-function{
    $var = "function"
    return $var
}

$var
$var = invoke-command -ComputerName NameOfComputer -scriptblock  ${function:do-function}
$var

Also, a scriptblock can be defined as follow:

$myScriptBlock = {
    # ....
}

invoke-command -ComputerName NameOfComputer -scriptblock $myScriptBlock
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172