gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:41:33 31 4
gpt4 key购买 nike

考虑以下语句:

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 itsoperands to bool, if necessary (§6.2). The result is the logical ANDof the possibly converted operand values, and has type bool. If theleft operand evaluates to False the right operand is not evaluated.The logical OR operator -or converts the values designated by itsoperands to bool, if necessary (§6.2). The result is the logical OR ofthe possibly converted operand values, and has type bool. If the leftoperand evaluates to True the right operand is not evaluated. Thelogical XOR operator -xor converts the values designated by itsoperands to bool (§6.2). The result is the logical XOR of the possiblyconverted operand values, and has type bool.

These operators are left associative.


所以这决定了添加(或不)括号的规则。

关于powershell - 使用括号进行多个逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551600/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com