0

I am trying to access the array variable outside the invoke command. I tried the below code, where I cannot access the remote array variable from my local session.

$serverlist = @("server1", "server2")

foreach ($server in $serverlist) {
    #Write-Host $computer

    $vinodh = Invoke-Command -ComputerName $server -ScriptBlock {
        $testVar = @("Stack", "over", "flow")
    }
}
foreach ($vars in $testVar) {
    Write-Host $vars # Unable to get the values as stack,over, flow
}

Actual results: unable to get values.

I expect the output as

stack
over
flow

1 Answer 1

1

Variables set inside the remote session were not populated to the local powershell session (About Scopes). You could return the values from the invoked session for using later.

$ReturnValues = Invoke-Command -ComputerName $Server -ScriptBlock {
    $testVar=@("Stack","over","flow")
    return  $testVar #return data
}

foreach ($ReturnValue in $ReturnValues)
{
    $ReturnValue
}
Sign up to request clarification or add additional context in comments.

3 Comments

Note that using the return keyword is not required. PowerShell by default returns all non-captured regular output.
Thanks for your response, can we return multiple array variable ?
Can we return multiple array variable and then i need to iterate each of them using for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.