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?