0

Consider the below code:

Set-Variable -Name session -Value $null -Scope Global

function Manage-SecondAdmin {
    Close-Session
    $session = Open-Session
}

$session = Open-Session
Manage-SecondAdmin
$x = Invoke-Session $session
# Outputs success string or nothing in case of failure
if ($x) {
    # Does not come here
    Write-Host "Success"
} else {
    # Comes here
    Write-Host "Invalid session ID"
    $session = Open-Session
}
$x = Invoke-Session $session
# Now successful response

When I use the above code, it always go to else part as explained in the command. I am aware of the keyword 'global'. Is it needed when I use 'Set-Variable'? What is the best approach for this?

1
  • @AdminOfThings, Updated the question with comment. Commented Aug 27, 2019 at 5:53

1 Answer 1

1

$session in Manage-SecondAdmin is a different variable than $global:session. Apparently Close-Session (whatever that cmdlet might be) closes the existing session, and the subsequent Open-Session opens a new one, which is then assigned it to the local variable $session in the scope of the function while the global variable $session still holds the reference to the now closed session. You could probably fix that by changing $session to $global:session, but manipulating global variables in nested contexts is a bad practice. Don't do that.

Have the function return the new session and assign the return value to a variable where the function is called:

function Manage-SecondAdmin {
    Close-Session
    Open-Session
}

$session = Open-Session
$session = Manage-SecondAdmin
...

Pre-defining your variables with Set-Variable normally isn't required in PowerShell.

Sign up to request clarification or add additional context in comments.

Comments

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.