1

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Eric Furspan
  • 742
  • 3
  • 15
  • 36
  • You don't unless you return them from the command. It's literally the first line in the help document: `The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands` – Maximilian Burszley Jan 10 '18 at 22:33
  • Please take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution. What do you think you need this for? – Ansgar Wiechers Jan 10 '18 at 22:40

3 Answers3

6

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 
Mike Shepard
  • 17,466
  • 6
  • 51
  • 69
2

Return both values in the scriptblock and assign a variable to your invoke-command. You can then access the variables from the returned array:

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

$remoteOutput = Invoke-Command $myValues
$remoteOutput[0]
$remoteOutput[1]

The output as tested on my computer will be:

hello
world

Let me know if this solves the problem you are having. If not we can work toward a different solution!

B3W
  • 166
  • 11
0

A requirement to frequently re-initialize variables usually indicates poor design. With that said, if for some reason you still must do that I'd use a function to (re-)initialize the variable set in the global or script scope:

function Initialize-VariableSet {
    $script:value1 = 'hello'
    $script:value2 = 'world'
}

Demonstration:

PS C:\> Initialize-VariableSet
PS C:\> $value1
hello
PS C:\> $value1 = 'foobar'
PS C:\> $value1
foobar
PS C:\> Initialize-VariableSet
PS C:\> $value1
hello
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Won't get into the complex reason why I need to re-init the vars but its a good enough reason and ill leave it at that. Thanks for the reply! – Eric Furspan Jan 10 '18 at 23:01