开发者

How to test for existence of a script-scoped variable in PowerShell?

Is it possible to test for the existence of a script-scoped variable in PowerShell?

I've been using the PowerShell Community Extensions (PSCX) but I've noticed that if you import the module while Set-PSDebug -Strict is set, an error is produced:

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

While investigating how I might fix this, I found this piece of code in Pscx.Get开发者_如何学运维Help.psm1:

#requires -version 2.0

param([string[]]$PreCacheList)

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

This is pretty straight forward code; if the cache doesn't exist or needs to be refreshed, create a new, empty cache. The problem is that calling $SCRIPT:helpCache while Set-PSDebug -Strict is in force casues the error because the variable hasn't been defined yet.

Ideally, we could use a Test-Variable cmdlet but such a thing doesn't exist! I thought about looking in the variable: provider but I don't know how to determine the scope of a variable.

So my question is: how can I test for the existence of a variable while Set-PSDebug -Strict is in force, without causing an error?


Use test-path variable:SCRIPT:helpCache

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

This works for me without problems. Checked using this code:

@'
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


Try this trick:

Get-Variable [h]elpCache -Scope Script

It should not throw or emit any errors because we use a wildcard [h]elpCache. On the other hand this kind of a wildcard is a literal name de facto.


You can use Get-Variable with the -Scope parameter. This cmdlet will (by default at least) not return only the variable's value but a PSVariable object and will throw an exception if the variable isn't found:

Get-Variable foo -Scope script
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜