考虑以下语句:
Get-ChildItem -Recurse *.vbs | Where-Object{$_.name -like "d*" -and $_.name -like "*s"}
Get-ChildItem -Recurse *.vbs | Where-Object{($_.name -like "d*") -and ($_.name -like "*s")}
它们将产生完全相同的输出。我一直假设第一个语句会失败,因为条件不在括号中。
看着 about_Logical_Operators
-and
的示例和 -or
显示这些括号。(1 -eq 1) -or (1 -eq 2)
但随后科技网文章为Using the Where-Object Cmdlet显示这个例子
$_.handles -gt 200 -and $_.name -eq "svchost"
有一段时间我一直在告诉人们使用括号,因为“否则它就行不通”。区别是否纯粹是装饰性的,最终无关紧要,我只是在插入我的个人喜好?
最佳答案
如果你看 Windows PowerShell 3.0 Specification document ,它在第 7.10 节(逻辑运算符)中说:
The logical AND operator -and converts the values designated by its operands to bool, if necessary (§6.2). The result is the logical AND of the possibly converted operand values, and has type bool. If the left operand evaluates to False the right operand is not evaluated. The logical OR operator -or converts the values designated by its operands to bool, if necessary (§6.2). The result is the logical OR of the possibly converted operand values, and has type bool. If the left operand evaluates to True the right operand is not evaluated. The logical XOR operator -xor converts the values designated by its operands to bool (§6.2). The result is the logical XOR of the possibly converted operand values, and has type bool.
These operators are left associative.
所以这决定了添加(或不)括号的规则。
关于powershell - 使用括号进行多个逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551600/