Operators are used to perform specific operations on data, often stored in a variable. PowerShell offers multiple types of operators to manipulate data, including:
- Arithmetic Operators
- Assignment Operators
- Unary Operators
- Comparison Operators
- Logical Operators
Arithmetic Operators
First, let’s discuss arithmetic operators used to calculate numeric values. Arithmetic operators include:
+
(Addition): adds numbers and concatenates strings-
(Subtraction): subtracts or negates numbers*
(Multiplication): multiplies numbers or copies strings a specified number of times/
(Division): divides numbers%
(Modulus): returns the remainder of a division operation
PS > 5 + 5 10 PS > 25 % 3 # 25/3 = 8 remainder 1 1
Arithmetic operators are binary, meaning they require two operands to calculate the result. As we can see in the examples above, the syntax for arithmetic operators is <Operand_1> <Arithmetic-Operator> <Operand_2>
. Operators are best utilized when used with variables, as shown below.
PS > $number = 25 PS > $number / 5 5 PS > $number = $number * 3 PS > $number 75
Arithmetic Operators on Strings
PowerShell allows us to manipulate strings using the addition +
and multiplication *
operators. The +
operator concatenates strings, whereas the *
operator copies the string a specified number of times.
PS > $best_learning_platform = "Code" + "cademy" PS > $punctuation = "!" * 3 PS > $best_learning_platform + $punctuation Codecademy!!!
You can see two strings are joined to create the string "codecademy"
and three exclamation points are made into a string by multiplying "!"
by 3
.
Instructions
In the PowerShell terminal, add two numbers 5
and 2
.
When you’re done, click the Check Work button.
Now subtract 7
from 49
in the terminal.
When you’re done, click the Check Work button.
Multiply the string "hello"
by 3.
When you’re done, click the Check Work button.
Next, divide the number 64.209
by 3
.
When you’re done, click the Check Work button.
Finally, get the remainder of the division of 39
by 4
.
When you’re done, click the Check Work button.