如何在Powershell中将test-path用于变量属性?

时间:2019-08-21 19:50:20

标签: powershell null

我想使用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被设置为一个值。在启用严格模式($null或更高)的情况下,如何正确检查此Set-StrictMode -Version 2状态?

3 个答案:

答案 0 :(得分:0)

$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

答案 1 :(得分:0)

您不能以这种方式引用属性。

dir variable:\MyVariable | select -expand value

cat dog
--- ---
  1

答案 2 :(得分:0)

要验证变量的存在,并检查存储为变量值的对象(如果有)是否具有具有给定名称的属性,即使有效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


关于您尝试过的事情

您只能在传递给Variable:的{​​{1}}基于驱动器的路径中使用变量 names ,您不能引用变量的 value 属性。

Test-Path查找字面上名为 Test-Path variable:\MyVariable.cat的变量,该变量不存在。