简体   繁体   中英

How to declare global variable using Set-Variable in PowerShell?

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?

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM