如何测试PowerShell中是否存在脚本范围的变量?

Dam*_*ell 7 powershell

是否有可能在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在有效的情况下测试变量的存在,而不会导致错误?

ste*_*tej 5

使用 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)

  • 这可能是最好的方法.[h] elpCache的技巧更快(只是一点点),但它是hacky.此外,当变量名称本身就是变量时,Test-Path方式要好得多,即Test-Path变量:script:$ name (2认同)