【问题标题】:How do I use test-path in Powershell for a variable property?如何在 Powershell 中将测试路径用于变量属性?
【发布时间】:2019-08-27 21:34:45
【问题描述】:

我想使用 strictmode 并正确检查 null 状态。我不确定如何使用变量属性的测试路径来做到这一点。

$MyVariable = [pscustomobject]@{
    cat = $null
    dog = $null
}

$MyVariable.cat = 1

Test-Path variable:\MyVariable
Test-Path variable:\MyVariable.cat
Test-Path variable:\MyVariable.dog

这给出了输出:

True
False
False

我希望看到这个:

True
True
False

因为$myVariable.cat 被设置为一个值。如何在启用严格模式(Set-StrictMode -Version 2 或更高版本)的情况下正确检查此 $null 状态?

【问题讨论】:

    标签: powershell null


    【解决方案1】:

    验证变量的存在并检查作为其值存储的对象(如果有)是否具有给定名称的属性,即使Set-StrictMode -Version Latest 有效:

    (Test-Path variable:MyVariable) -and 
      $null -ne $MyVariable -and 
        $MyVariable.psobject.Properties['cat']
    

    请注意,以上测试属性的存在,而不考虑其(可能是$null,如您的情况)。

    访问具有属性名称的非$null 变量的.psobject.Properties 集合从不 会引发错误,即使使用Set-StrictMode -Version Latest(从PowerShell Core 7.0.0-preview.3 开始);如果不存在这样的属性,则返回 $null,在 -and 操作的上下文中计算为 $false


    至于你尝试了什么

    您只能在传递给Test-Path 的基于Variable:drive 的路径中使用变量names,不能引用变量的 或其属性。 p>

    Test-Path variable:\MyVariable.cat 查找一个不存在的变量命名 MyVariable.cat

    【讨论】:

      【解决方案2】:
      $MyVariable = [pscustomobject]@{
          cat = $null
          dog = $null
      }
      
      $MyVariable.cat = 1
      
      if($cat -eq $null){
          Write-Output("null!")
      }
      else{
          Write-Output("not null!")
      }
      
      if($do-eq $null){
          Write-Output("null!")
      }
      else{
          Write-Output("not null!")
      }
      if($MyVariable.cat -eq $null){
          Write-Output("null!")
      }
      else{
          Write-Output("not null!")
      }
      

      If else 语句检查所有变量是否等于$null

      【讨论】:

        【解决方案3】:

        你不能这样引用属性。

        dir variable:\MyVariable | select -expand value
        
        cat dog
        --- ---
          1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-26
          • 2019-12-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多