我想使用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
状态?
答案 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
的变量,该变量不存在。