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

前端 未结 9 1680
暖寄归人
暖寄归人 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 18:53

    EDIT: Use stej's answer below. My own (partially incorrect) one is still reproduced here for reference:


    You can use

    Get-Variable foo -Scope Global
    

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

    0 讨论(0)
  • 2020-12-07 18:54

    Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)

    0 讨论(0)
  • 2020-12-07 18:55

    There's an even easier way:

    if ($variable)
    {
        Write-Host "bar exist"
    }
    else
    {
        Write-Host "bar does not exists"
    }
    
    0 讨论(0)
  • 2020-12-07 19:11

    You can assign a variable to the return value of Get-Variable then check to see if it is null:

    $variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue
    
    if ($variable -eq $null)
    {
        Write-Host "foo does not exist"
    }
    
    # else...
    

    Just be aware that the variable has to be assigned to something for it to "exist". For example:

    $global:foo = $null
    
    $variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue
    
    if ($variable -eq $null)
    {
        Write-Host "foo does not exist"
    }
    else
    {
        Write-Host "foo exists"
    }
    
    $global:bar
    
    $variable = Get-Variable -Name bar -Scope Global -ErrorAction SilentlyContinue
    
    if ($variable -eq $null)
    {
        Write-Host "bar does not exist"
    }
    else
    {
        Write-Host "bar exists"
    }
    

    Output:

    foo exists
    bar does not exist
    
    0 讨论(0)
  • 2020-12-07 19:11

    Test the existence of variavle MyVariable. Returns boolean true or false.

     Test-Path variable:\MyVariable

    0 讨论(0)
  • 2020-12-07 19:16

    Test-Path can be used with a special syntax:

    Test-Path variable:global:foo
    

    This also works for environment variables ($env:foo):

    Test-Path env:foo
    

    And for non-global variables (just $foo inline):

    Test-Path variable:foo
    
    0 讨论(0)
提交回复
热议问题