In PowerShell, how do I test whether or not a specific variable exists in global scope?

前端 未结 9 1707
暖寄归人
暖寄归人 2020-12-07 18:34

I\'m using PowerShell scripts for some UI automation of a WPF application. Normally, the scripts are run as a group, based on the value of a global variable. It\'s a littl

9条回答
  •  被撕碎了的回忆
    2020-12-07 19:18

    Personal preference is to use Ignore over SilentlyContinue here because it's not an error at all. Since we're expecting it to potentially be $false let's prevent it (with Ignore) from being put (albeit silently) in the $Error stack.

    You can use:

    if (Get-Variable 'foo' -Scope 'Global' -ErrorAction 'Ignore') {
        $true
    } else {
        $false
    }
    

    More tersely:

    [bool](gv foo -s global -ea ig)
    

    Output of either:

    False
    

    Alternatively

    You can trap the error that is raised when the variable doesn't exist.

    try {
        Get-Variable foo -Scope Global -ErrorAction 'Stop'
    } catch [System.Management.Automation.ItemNotFoundException] {
        Write-Warning $_
    }
    

    Outputs:

    WARNING: Cannot find a variable with the name 'foo'.
    

提交回复
热议问题