powershell - 使用括号进行多个逻辑运算

标签 powershell logical-operators parentheses

考虑以下语句:

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/

相关文章:

powershell - 在 powershell 中创建目录快捷方式

powershell - 在powershell中将参数传递给Set-Alias的正确方法是什么?

powershell - ArrayList .Add 与 .AddRange 对比管道

c# - 从 C# 调用远程 powershell 命令

c++ - 如何比较 char 或 string 变量是否等于某个字符串?

c - C 中使用数组堆栈的括号检查器每次都不会产生正确的输出

Java:何时在方法后面使用括号

c++ - IF 语句中的多个 OR 或 AND 条件

java - if条件检查在JAVA中的任何一点是否只有一个变量是四个变量的集合

ruby - 试图找到 : . (eval):289 的文件/行:警告:不要在参数括号前放置空格