We use Arithmetic Operators in the expressions to calculate numeric values. PowerShell processes these expressions from left to right, and depending on the order of precedence expressions are evaluated.
Operators who have higher precedence will evaluate first. To understand operator precedence, let’s take a simple arithmetic expression;
3+4/7*10-2%3+20
When we evaluate the above expression from left to right, we will get the result 22
. When PowerShell evaluates the expression from left to right, it also considers the precedence of the operators used in the expression, and you will see the different results.
PS C:\> 3+4/7*10-2%3+20 26.7142857142857
For better readability, it is suggested to use parentheses wherever required in the expression which helps to avoid any confusion; and also it has higher precedence in PowerShell, hence expressions within parentheses will evaluate first.
The below table will help to understand the precedence of each arithmetic operator used in PowerShell.
Operator(s) | Description | Precedence |
() | Parentheses | 1 |
– | Negative number / Unary operator | 2 |
*, /, % | Multiplication & Division | 3 |
+, – | Addition & Subtraction | 4 |
-band, -bor, -bxor, -bnot, -shr, -shl | Bitwise operators | 5 |
Observe that, some operators have the same precedence, and if these occurred in the expression, PowerShell will evaluate the one which is in first from left to right. Look at the below expressions, to understand better;
PS C:\> 3%2*2 2 PS C:\> 3*2%2 0
As mentioned above, for better readability & if you want to give more importance to the expression, place the expression in parentheses which has more precedence in PowerShell.
[..] David