Using brackets for multiple logical operations
Consider the following statements:
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")}
They will get accurate results. I always assumed that the first statement would fail as the conditions were not in parentheses.
The examples about_Logical_Operators for -and
and -or
show these parentheses.
(1 -eq 1) -or (1 -eq 2)
But then a technical networking article for Using the Where-Object Cmdlet shows this example
$_.handles -gt 200 -and $_.name -eq "svchost"
For a while, I told people to use parentheses because "it didn't work otherwise." Is the difference purely cosmetic and ultimately irrelevant and am I just pushing my personal preference?
source to share
If you look at the Windows PowerShell 3.0 Specification Document , it says so in section 7.10 (Boolean Operators):
The logical operator AND - and converts the values indicated by its operands to bool, if necessary (§6.2). The result is a logical AND of the possibly converted operand values and is of type bool. If the left operand evaluates to False, the right operand is not evaluated. The logical operator OR or converts the values indicated by its operands to bool, if necessary (§6.2). The result is a logical OR of the possibly converted operand values, and is of 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 a logical XOR, possibly the converted values of the operands, and is of type bool.
These operators remain associative.
So it defines the rules for adding (or not) parentheses.
source to share