The basic arithmetic operators include those to add, multiply, subtract, divide, and calculate the remainder of a division. Table 1 lists these operators.
Table 1. Windows PowerShell Arithmetic Operators
Operator | Description |
---|
+ | Adds two values |
- | Subtracts one value from another |
* | Multiplies two values |
/ | Divides one value by another |
% | Returns the remainder from a division |
Let’s take a closer look at the + operator. To add the values 1 and 5 together, you could type this:
To add a string with a numeric value, use this form:
It is also possible to add multiple string values to
build up a single string. This example uses the + operator to build up
a URL from three strings:
PS > "http://" + "SPServer01" + "/MySite"
http://SPServer01/MySite
You can also add string objects stored in variables together.
PS > $url = "http://SPServer01"
PS > $web = "MySite"
PS > $url + "/" + $web
http://SPServer01/MySite
However, it is not possible to add a string to a numeric value.
PS > 1 + ";#" + "Item"
Cannot convert value "String" to type "System.Int32".
Error: "Input string was not in a correct format."
At line:1 char:4
+ 1 + <<<< "String"
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
Windows PowerShell interprets the first argument as an instance of the type System.Int32. When we try to add a System.String value to a System.Int32 value, an error occurs. Windows PowerShell expects an argument of the type System.Int32, and it is not possible to convert a System.String value containing characters other than numeric ones. The following is the correct way to add the values:
PS > "1" + ";#" + "Item"
1;#Item
You can also cast the numeric value using the [string] type literal, which is a PowerShell alias for the System.String type.
PS > [string]1 + ";#" + "Item"
1;#Item
The value on the left side defines the type of the
whole operation. You can add a number to a string, since a number can
be converted to a string value, as shown in this example:
Here are examples of using the other arithmetic operators:
Use the – operator to subtract numeric values:
The - operator also works with negative numbers:
Use the * operator to multiply values:
You can also multiply string values with a numeric value:
PS > "Hello" * 5
HelloHelloHelloHelloHello
Divide numeric values with the / operator:
Use the modulus (%) operator to calculate remainders:
PS > 10 % 3
1
PS > 6 % 2
0