PowerShell Arithmetic Operators


The following are arithmetic operators in powerShell. 

+   Add integers, concatenates strings, arrays, and hash tables.
-    Substract one value with other value, Makes a number to be negative 
*   Multiply numbers, copy strings and arrays the specified number of times.
/    Divide two values
%  Return the remainder of a division operation 

Write-Host (3 + 4) # add two numbers
write-Host ("file" + "name") # concatenate strings
write-Host (@(1, 2) + @(3, 4)) # add two arrays
write-Host (@{"one" = 1} + @{"two" = 2}) # add two hash tables

Write-Host (9 - 2) # substract two numbers
Write-Host (-9) # make negative number

Write-Host (6 * 8) # multiplication
Write-Host ('powerShell' * 4) # copy string with specified number of times
Write-Host (@(1, 2, 3) * 3) # copy array with specified number of times

Write-Host (8 / 2)
Write-Host (7 % 2)

What about this example.

Write-Host ("apples" + 3)
Write-Host (3 + " apples") # error
Write-Host (4 * 'powerShell') # error
Write-Host (2 * @(1, 2, 3)) # error

Notice those errors. That's because operation that powerShell performs is determined by the Microsoft .NET Framework type of the leftmost object in the operation. PowerShell tries to convert all the objects in the operation to the .NET Framework type of the first object. If it succeeds in converting the objects, it performs the operation appropriate to the .NET Framework type of the first object. If it fails to convert any of the objects, the operation fails. So addition and multiplicatoin in powerShell are not strictly commutative, like (a + b) doesn't always equal (b + a), and (ab) doesn't always equal (ba). 

Operator Precedence

PowerShell processed arithmetic operators in the following order. PowerShell will evaluate the expressoin from left to right according with precedence rules. 

()             Parentheses
-              Negative number or unary operator
*, /, %     Multiplication and division
+, -          Addition and Substraction 

Write-Host (9 + 4/2*2) # 13
Write-Host (3 + 6/(2 * 3)) # 4
Write-Host ((2 + 3) / 5 * 10) # 10

Rounding 

PowerShell will round the value to the nearest integer. When it comes .5 it will be rounded to the nearest even integer.

Write-Host ([int] (3 / 2)) # 1.5 rounded to the nearest even ==> 2
Write-Host ([int] (5 / 2)) # 2.5 rounded to the nearest even ==> 2
Write-Host ([int] (8 / 6)) # 1.6 rounded to the nearest int ==> 1
Write-Host ([int] (7 / 2)) # 3.5 rounded to the nearest even ==> 4

Subscribe to receive free email updates:

0 Response to "PowerShell Arithmetic Operators "

Post a Comment