Ying Li at myITforum.com

PowerShell & System Center

The basic arithmetic operators in PowerShell and the all important "Left Hand" rule!

Here are basic arithmetic operators in PowerShell:

The addition operator – Add two values together

Example:    2 + 4 = 6

                “Hello” + “World” = “Hello World”

                1,2,3 + 4,5,6 = 1,2,3,4,5,6

The multiplication operator – Multiply 2 values

Example:    2 * 4 = 8

                “x” * 3 = “xxx”

                1,2 * 2 = 1,2,1,2

The subtraction operator – Subtract one value from another

Example:     8 – 4 =  4

The division operator – Divide two values

Example:     8 / 4 = 2

                 9 / 6 = 1.5

The modulus operator – Return the remainder from a division operation

Example:     7 % 4 = 3

As you can see, when we adding or multiplying two numbers produces a numeric result. Adding two stings performs a string concatenation, resulting a new string, and adding two arrays joins the two arrays (array catenation), producing a new array. It’s get interesting when you mix operand types. In this situation, the type of left operand determines how the operation will proceed ( “Left-Hand” rule!). Let’s see the below example:

PS P:\>  5 + "125"
130

Left operand is number, PowerShell convert the right operand to a number


PS P:\> "5" + 125
5125

Left operand is string, the operand on the right (the number 125) is converted to a string and appended to “5” to produce a new sting “5125”

If the right operand can’t be converted into the type of the left operand then a type conversion error will be raised:

PS P:\> 5 + "xyz"
Cannot convert value "xyz" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:4
+ 5 +  <<<< "xyz"

You got the idea…

Posted: Jun 18 2007, 09:47 AM by yli628 | with no comments
Filed under:

Comments

No Comments