Powershell where-object-notlike

Powershell where-object-notlike

如果我通过管道连接到where-object { $_.someProperty -notlike "*someValue*" }-notlike似乎不仅仅过滤匹配项,还过滤someProperty为空的对象。

where-object -notlike来自 TechNet:

Specifies the Not-Like operator, which gets objects when the property value does not match a value that includes wildcard characters.

根据定义,为什么-notlike不返回为空的对象someProperty?因为没有找到匹配项?

只是为了澄清一下:我正在表演Get-ADComputer -Filter * -Property MemberOf,someotherstuff,someotherstuff | where-object { $_.memberof -notlike "*somepartialdn*" }

期望返回计算机对象,因为没有匹配项,即使属性值为空。

答案1

这取决于你对“空”的定义。

如果someProperty没有值,则其有效值为$null。您的字符串比较不适用于$null

如果someProperty为空字符串(""[String]::Empty),则应用字符串比较。

$values = "indonesia","turkmenistan",$null,"columbia"
$values |Where-Object {$_ -notlike "*istan"}
# Results in @("indonesia","columbia")

$values = "indonesia","turkmenistan",[String]::Empty,"columbia"
$values |Where-Object {$_ -notlike "*istan"}
# Results in @("indonesia","","columbia")

答案2

这只是一个猜测,但您可以通过执行以下操作来解决它:

where-object { $_.someProperty -ne "" -and $_.someProperty -notlike "*someValue*" }

我很确定您所遇到的情况是由于数据以字符串形式传输...因此空值被视为""

相关内容