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

前端 未结 9 1681
暖寄归人
暖寄归人 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'.
    
    0 讨论(0)
  • 2020-12-07 19:18

    So far, it looks like the answer that works is this one.

    To break it out further, what worked for me was this:

    Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

    $? returns either true or false.

    0 讨论(0)
  • 2020-12-07 19:18
    $myvar = if ($env:variable) { $env:variable } else { "default_value" } 
    
    0 讨论(0)
提交回复
热议问题