Comparison operators are used to compare values, test conditions, or filter elements of a collection, such as an array. They return a Boolean value, True
or False
, as a result.
Equality Operators
Some of the comparison operators in PowerShell are called equality operators. They are binary operators that compare two integer or string values that return True
if the operator condition is met; otherwise, False
.
Operator | Description |
---|---|
-eq |
Checks if the two operand values are an exact match |
-ne |
Checks if the two operand values are NOT an exact match |
-gt |
Checks if the value of the left operand is greater than the value of the right operand |
-lt |
Checks if the value of the left operand is less than the value of the right operand |
-ge |
Checks if the value of the left operand is greater OR equal to the value of the right operand |
-le |
Checks if the value of the left operand is less OR equal to the value of the right operand |
Let’s take a look at a few examples.
-eq
and -ne
In the example below, -eq
returns True
because $my_num
matches the value 5
. When we use the ne
operator on the same operands, it returns False
since it only returns True
when the two values are NOT a match.
PS > $my_num = 5 PS > $my_num -eq 5 True PS > $my_num -ne 5 False
The -eq
and -ne
also work on strings, as shown below.
PS > "tomato" -ne "vegetable" True
-gt
and -lt
The first expression in the example below returns True
since 7
is greater than 2
. 42
is not less than 42
, so the second expression returns False
.
PS > 7 -gt 2 True PS > 42 -lt 42 False
-ge
and -le
In the example below, 3
is not greater than or equal to 6
, so False
is returned, and 42
is less than or equal to 42
, so True
is returned.
PS > 3 -ge 6 False PS > 42 -le 42 True
Instructions
In the PowerShell terminal, check if the string "happy"
is equal to the string "coding"
.
Click the Check Work button to continue.
Using the greater than operator, check if the integer 5
is greater than the integer 2
.
Click the Check Work button to continue.
Using the less than or equal operator, check if 43.15
is less than or equal to 43.15
.
Click the Check Work button to continue.