Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parenthesis 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 produce the exact same output. I have always assumed that the first statement would fail since the conditions were not in parentheses.

Looking at about_Logical_Operators the examples for -and and -or show these parentheses.

(1 -eq 1) -or (1 -eq 2)

But then the tech net article for Using the Where-Object Cmdlet shows this example

$_.handles -gt 200 -and $_.name -eq "svchost"

For a while I have been telling people to use the brackets because "otherwise it would not work". Is the difference purely cosmetic and ultimately not matter and I'm just pushing my personal preference?

like image 905
Matt Avatar asked Oct 21 '22 02:10

Matt


1 Answers

If you look at the Windows PowerShell 3.0 Specification document, it says this in section 7.10 (Logical Operators):

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.

So this determines the rules for adding (or not) parentheses.

like image 73
David Brabant Avatar answered Oct 23 '22 03:10

David Brabant