Assignment operators are used to assign one or more
values to a variable, modify values in a variable, or add values to a
variable. Table 1 shows the assignment operators available in Windows PowerShell.
Table 1. Windows PowerShell 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 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 assigns the remainder to the variable |
++ | Increases the value by one |
−− | Decreases the value by one |
The most common assignment operator is the equal operator (=). You can use the equal operator to assign a value to a variable.
PS > $variable = 1
PS > $variable
1
You can also assign the same value to multiple variables.
PS > $variable1 = $variable2 = 3
PS > $variable1
3
PS > $variable2
3
Here are examples of using some of the other assignment operators:
To increase the value of a variable by a specific value, use the += operator:
PS > $variable = "Windows"
PS > $variable += " "
PS > $variable += "PowerShell"
PS > $variable
Windows PowerShell
To decrease a variable with a specific value, use the -= operator:
PS > $variable = 5
PS > $variable -= 3
PS > $variable
2
To multiply a variable with a specific value, use the *= operator:
PS > $variable = "-"
PS > $variable *= 8
PS > $variable
--------
To increase a numeric value by one, use the ++ operator:
PS > $variable = 1
PS > $variable ++
PS > $variable
2
To decrease a numeric value by one, use the -- operator:
PS > $variable = 0
PS > $variable --
PS > $variable
-1