Using Windows PowerShell as an IT Pro – Part 15
In my last post I reviewed Arithmetic Operators. Now I will explore Assignment Operators.Assignment operators assign one or more values to a variable and perform numeric operations on the values before the assignment. Windows PowerShell supports the following assignment operators.
Operator | Description |
= | Sets the value of a variable to the specified value. |
+= | Increases the value of a variable by the specified value, or appends the specified value to the existing value. |
-= | Decreases the value of a variable by the specified value. |
*= | Multiplies the value of a variable by the specified value, or appends the specified value to the existing value. |
/= | Divides the value of a variable by the specified value. |
%= | Divides the value of a variable by the specified value and then assigns the remainder (modulus) to the variable. |
++ | Increases the value of a variable, assignable property, or array element by 1. |
– | Decreases the value of a variable, assignable property, or array element by 1. |
The assignment by addition, subtraction, multiplication, and division operators all work more or less the same way. For numeric types it takes the first part of the operator (+, -, *, /) and performs the appropriate calculation and then it assigns the result. For strings, it appends the specified value to the existing value. The assignment by subtraction and division operators do not work with strings. Let’s take a closer look at several of these operators.
The assignment by addition operator (+=) either increments the value of a variable or appends the specified value to the existing value. The action depends on whether the variable has a numeric or string type and whether the variable contains a single value (a scalar) or multiple values (a collection). First, it adds, and then it assigns.
$a = 5
$a += 2
$a
When the value of the variable is a string, the value on the right side of the operator is appended to the string.
$a = "String"
$a += ” Appended”
$a
The assignment by subtraction operator (-=) decrements the value of a variable by the value that is specified on the right side of the operator. This operator cannot be used with string variables and it cannot be used to remove an element from a collection. First, it subtracts, and then it assigns.
$a = 5
$a -= 2
$a
The increment operator (++) increases the value of a variable by 1. When you use the increment operator in a simple statement, no value is returned.
$a = 6
++$a
$a
The decrement operator (–) decreases the value of a variable by 1. As with the increment operator, no value is returned when you use the operator in a simple statement. Use parentheses to return a value.
$a = 6
(–$a)
In my next post we will examine Comparison Operators.
No comments:
Post a Comment