2015-09-28 92 views
0

有没有办法在where语句中组合多个逻辑运算符的参数?组合多个逻辑运算符

基本上我有这样的语句:

<command chain> | where {$_.user.tostring() -ne "USER1" -and $_.user.tostring() -ne "USER2" -and $_.user.tostring() -ne "USER3"} 

它实际上是一个相当长的链条,所以我想使之成为像这样简化它:

<command chain> | where {$_.user.tostring() -ne {"USER1" -or "USER2" -or "USER3"}} 

的以上声明不起作用,所以有什么建议请关于如何去做这件事?

回答

2

你想用这样的:

where {$_.user.tostring() -notin ("USER1","USER2","USER3")} 

或者这样:

where {($_.user.tostring() -ne "USER1") -and ($_.user.tostring() -ne "USER2") -and ($_.user.tostring() -ne "USER3") } 

那是因为你可以得到真的一样简单。一般来说,布尔运算符只能用于组合比较运算符(或其他你知道表示布尔值的东西)。


您的代码在这里:

where {$_.user.tostring() -ne {"USER1" -or "USER2" -or "USER3"}} 

这基本上是无稽之谈。它总是要评估为真。 {"USER1" -or "USER2" -or "USER3"}是数据类型ScriptBlock。

PS C:\> ({"USER1" -or "USER2" -or "USER3"}).GetType().FullName 
System.Management.Automation.ScriptBlock 

相信PowerShell中会投这一个字符串,但即使它被转换为字符串,它仍然没有评估为布尔表达式:

PS C:> ({"USER1" -or "USER2" -or "USER3"}).ToString() 
"USER1" -or "USER2" -or "USER3" 

那将评估为True,除非用户是从字面上“‘USER1’ - 或‘用户2’OR‘USER3’”

如果你改变它,以便它是一种附带性的表达,而不是一个脚本块:

where {$_.user.tostring() -ne ("USER1" -or "USER2" -or "USER3")} 

那么它永远是真的。 ("USER1" -or "USER2" -or "USER3")是布尔类型,并且将始终具有值true。

PS C:\> ("USER1" -or "USER2" -or "USER3") 
True 

所以你基本上是运行:

where {$_.user.tostring() -ne $true } 

再有,就算PowerShell的一切都转换为字符串像我想会的,这是不可思议的事,你已经有了一个用户名为“真” 。所以这将永远是事实。

0

假设你处理的是一个数组它可以在你写的这个类似的方式来完成,甚至更短的检查了这一点:

PS Z:\> @("food","drink","cheese","dog") -match "(food|cheese)" 
food 
cheese 

PS Z:\> @("food","drink","cheese","dog") -notmatch "(food|cheese)" 
drink 
dog 

where clause: 

PS Z:\> @("food","drink","cheese","dog") | where {$_ -notmatch "(food|cheese)"} 
drink 
dog