代码之家  ›  专栏  ›  技术社区  ›  Scott Lawrence

在PowerShell中,如何测试全局范围中是否存在特定变量?

  •  46
  • Scott Lawrence  · 技术社区  · 16 年前

    我正在使用PowerShell脚本实现WPF应用程序的一些UI自动化。通常,基于全局变量的值,脚本作为一个组运行。当我只想运行一个脚本时,手动设置这个变量有点不方便,所以我正在寻找一种方法来修改它们,检查这个变量,如果找不到就设置它。

    测试路径变量:\foo似乎不起作用,因为仍然出现以下错误:

    变量'$global:foo'无法检索,因为尚未设置它。

    7 回复  |  直到 16 年前
        1
  •  27
  •   citelao Alson B Ching    6 年前

    编辑: 使用 stej's answer 在下面。我自己的(部分不正确)一个仍然复制在这里作为参考:


    Get-Variable foo -Scope Global
    

    并捕获变量不存在时引发的错误。

        2
  •  230
  •   citelao Alson B Ching    6 年前

    Test-Path

    Test-Path variable:global:foo
    

    这也适用于环境变量( $env:foo

    Test-Path env:foo
    

    对于非全局变量(仅 $foo 内联):

    Test-Path variable:foo
    
        3
  •  18
  •   VertigoRay Jose Luis Quichimbo    6 年前

    Ignore 结束 SilentlyContinue 因为这根本不是一个错误。因为我们预计它可能 $false 让我们(用英语)阻止它 忽略 )从被放(尽管是无声的)在 $Error

    您可以使用:

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

    更简洁地说:

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

    输出:

    False
    

    或者

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

    输出:

    WARNING: Cannot find a variable with the name 'foo'.
    
        4
  •  4
  •   George Howarth    16 年前

    您可以将一个变量赋给Get variable的返回值,然后检查它是否为null:

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

    只需注意,变量必须分配给某个对象才能“存在”。例如:

    $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"
    }
    

    输出:

    foo exists
    bar does not exist
    
        5
  •  3
  •   KeesG    11 年前

    [布尔](获取变量“Varname”-ErrorAction SilentlyContinue)

        6
  •  2
  •   Scott Lawrence    16 年前

    到目前为止,有效的答案似乎是 this one .

    更进一步说,对我有效的是:

    获取变量-Name foo-Scope Global-ea SilentlyContinue | out null

    $? 返回true或false。

        7
  •  1
  •   Shirish Shukla    7 年前
    $myvar = if ($env:variable) { $env:variable } else { "default_value" } 
    
        8
  •  0
  •   Prathamesh Koshti    5 年前

    测试variavle MyVariable是否存在。 返回布尔值true或false。

    Test-Path variable:\MyVariable

        9
  •  -6
  •   Paras Joshi    13 年前

    还有一个更简单的方法:

    if ($variable)
    {
        Write-Host "bar exist"
    }
    else
    {
        Write-Host "bar does not exists"
    }
    
    推荐文章