我在PowerShell脚本中有以下代码:
Write-Host "clusterName=$clusterName"
Write-Host (Test-Path variable:global:clusterName)
返回以下输出:
clusterName=CorrectValue
False
现在显然变量存在(因为它包含值“CorrectValue”)但是如果是这种情况我会期望第二次调用Write-Host
返回“true”,而不是“false”。我在In PowerShell, how do I test whether or not a specific variable exists in global scope?找到了“Test-Path ...”代码,但很明显它的表现不像我想象的那样。任何人都可以解释原因吗?
TIA
答案 0 :(得分:0)
除非明确使用$global:
修饰符作为变量名,否则不会在全局范围内创建脚本中定义的变量。 (这通常是你想要的,因为全局变量在脚本完成后有一种趋势。)
您可以使用Test-Path variable:local:clusterName
更改测试函数以查看本地命名空间,或使用Test-Path variable:script:clusterName
更改脚本命名空间 - 这两者都应为$true
。