gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:16:53 25 4
gpt4 key购买 nike

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

我一直在使用PowerShell Community Extensions (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

在研究如何解决这个问题时,我在 Pscx.GetHelp.psm1 中发现了这段代码:
#requires -version 2.0

param([string[]]$PreCacheList)

if ((!$SCRIPT:helpCache) -or $RefreshCache) {
$SCRIPT:helpCache = @{}
}

这是非常直接的代码;如果缓存不存在或需要刷新,请创建一个新的空缓存。问题是调用 $SCRIPT:helpCacheSet-PSDebug -Strict is in force 会导致错误,因为尚 undefined variable 。

理想情况下,我们可以使用 Test-Variable cmdlet,但这样的事情不存在!我想看看 variable: provider 但我不知道如何确定变量的范围。

所以我的问题是:如何在 Set-PSDebug -Strict 时测试变量是否存在?是否有效,不会导致错误?

最佳答案

使用test-path variable:SCRIPT:helpCache

if (!(test-path variable:script:helpCache)) {
$script:helpCache = @{}
}

这对我来说没有问题。
使用此代码检查:
@'
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

关于powershell - 如何在 PowerShell 中测试脚本范围变量的存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2763900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com