How to check for script -scoped variable in PowerShell?

Can I check for the existence of a script -scoped variable in PowerShell?

I used PowerShell Community Extensions (PSCX) , but I noticed that if you import a module and Set-PSDebug -Strict - set an error occurs:

 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 

When researching how I can fix this, I found this piece of code in Pscx.GetHelp.psm1:

 #requires -version 2.0 param([string[]]$PreCacheList) if ((!$SCRIPT:helpCache) -or $RefreshCache) { $SCRIPT:helpCache = @{} } 

This is pretty simple code; if the cache does not exist or needs updating, create a new empty cache. The problem is that calling $SCRIPT:helpCache while Set-PSDebug -Strict is valid causes an error because the variable is not yet defined.

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

So my question is: how can I check for a variable while Set-PSDebug -Strict without causing an error?

+7
powershell
source share
3 answers

Use test-path variable:SCRIPT:helpCache

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

This works for me without a problem. Checked with 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 
+5
source share

Try this trick:

 Get-Variable [h]elpCache -Scope Script 

It should not throw or emit any errors, because we use the [h]elpCache . On the other hand, this type of template is the de facto name.

+4
source share

You can use Get-Variable with the -Scope parameter. This cmdlet (at least by default) does not return only the value of the variable, but the PSVariable object and throws an exception if the variable is not found:

 Get-Variable foo -Scope script 
+1
source share

All Articles