Just like in mathematics, the order in which operators are evaluated matters in programming. Operator precedence in PowerShell is as follows:
( )
++
--
!
-not
*
/
%
+
-
-is
-isnot
-as
-eq
-ne
-gt
-ge
-lt
-le
-contains
-notContains
-and
-or
-xor
=
+=
-=
*=
/=
%=
Precedence order is the order in which PowerShell evaluates the operators if multiple operators are used in the same expression. Parentheses ( )
take the highest priority, and the assignment operators have the least priority. Operators on the same level are evaluated from left to right. Consider the example below.
PS > 5 - 1 * 5 0
The multiplication operator *
has higher precedence than the subtraction operator -
. Thus, in the example above, the expression 1 * 5
is evaluated first, resulting in 5 - 5
, which equals 0
.
We can use parentheses to override the precedence order and force PowerShell to evaluate a part of an expression first.
PS > (5 - 1) * 5 20
Instructions
In the script file named expression_precedence.ps1
, we have three expressions that return 8
, 6
, and False
respectively. These results are not what we are looking for. Let’s use parentheses ( )
to acquire the desired results.
For expression_1
, we want 4
as a result. Put parentheses around the expression 2 + 4 * 2
.
Click Run when you’re done and your result will output in the terminal.
We want 2
to be the result of expression_2
. Enclose the expression 3 * (2 + 1)
with parentheses and click Run.
The way it is now, expression_3
is currently returning False
. We want this to be True
.
Remove parentheses around 3 + 2 -ne 5
and put parentheses around 2 -ne 5
instead.
Remove parentheses around 5 -gt 8
and put parenthesis around the -gt
operator expression 2 * 5 -gt 8
.
Click the Run button to run the script file expression_precedence.ps1
one last time. The three expressions should now return 4
, 2
, and True
respectively.