Search code examples
powershellinvoke-command

Accessing variables defined in a scriptblock after running Invoke-Command


I'll try to make this example as simple as possible.

$myValues = {
    $value1 = "hello"
    $value2 = "world"
}

Invoke-Command $myValues

How can I access $value1 and $value2 after the Invoke-Command executes?

Edit: The problem I am trying to solve is that I will have to initialize the variables within $myValues multiple times throughout my script. So I figured I would define the scriptblock ONCE at the top and then simply call Invoke-Command on $myVariables whenever I need to reinitialize the variables.


Solution

  • If you dot-source the scriptblock it will run in your current scope and the variables will be available afterwards.

    $myValues = { 
        $value1 = "hello"
        $value2 ="world"
    }
    
    . $myValues