2

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.

2
  • 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 Commented Jan 10, 2018 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? Commented Jan 10, 2018 at 22:40

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

1 Comment

THIS! exactly what I needed. Thank you
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!

Comments

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

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.