[英]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
. Manage-SecondAdmin
中的$session
是与$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. 显然,
Close-Session
(无论该cmdlet可能是什么)都会关闭现有会话,随后的Open-Session
将打开一个新Open-Session
,然后将其分配给函数范围内的局部变量$session
,而全局变量$session
仍然保留对现在关闭的会话的引用。 You could probably fix that by changing $session
to $global:session
, but manipulating global variables in nested contexts is a bad practice. 您可能可以通过将
$session
更改$session
$global:session
$session
来解决此问题,但是在嵌套上下文中操作全局变量是一种不好的做法。 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. 在PowerShell中,通常不需要使用
Set-Variable
预定义变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.