是否有可能在PowerShell中测试脚本范围变量的存在?
我一直在使用PowerShell社区扩展(PSCX),但我注意到如果在Set-PSDebug -Strict设置时导入模块,则会产生错误:
The variable '$SCRIPT:helpCache' cannot be retrieved because it has not been set.
At C:\Users\...\Modules\Pscx\Modules\GetHelp\Pscx.GetHelp.psm1:5 char:24
Run Code Online (Sandbox Code Playgroud)
在研究如何解决这个问题时,我在Pscx.GetHelp.psm1中找到了这段代码:
#requires -version 2.0
param([string[]]$PreCacheList)
if ((!$SCRIPT:helpCache) -or $RefreshCache) {
$SCRIPT:helpCache = @{}
}
Run Code Online (Sandbox Code Playgroud)
这是非常简单的代码; 如果缓存不存在或需要刷新,请创建一个新的空缓存.问题是调用$SCRIPT:helpCachewhile Set-PSDebug -Strict有效会导致错误,因为尚未定义变量.
理想情况下,我们可以使用Test-Variablecmdlet,但这样的东西不存在!我考虑过查看variable:提供程序,但我不知道如何确定变量的范围.
所以我的问题是:如何Set-PSDebug -Strict在有效的情况下测试变量的存在,而不会导致错误?
使用 test-path variable:SCRIPT:helpCache
if (!(test-path variable:script:helpCache)) {
$script:helpCache = @{}
}
Run Code Online (Sandbox Code Playgroud)
这对我没有问题.使用此代码检查:
@'
Set-PsDebug -strict
write-host (test-path variable:script:helpCache)
$script:helpCache = "this is test"
write-host (test-path variable:script:helpCache) and value is $script:helpCache
'@ | set-content stricttest.ps1
.\stricttest.ps1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3614 次 |
| 最近记录: |