Using Expressions in PowerShell to Compare Values

Posted by:

|

On:

|

A comparison is an expression that results in True or False based on two values. There are many operators, and they can be compare many different types of values.

Comparison OperatorDefinition
-eqEqual to
-neNot equal to
-gtGreater than
-geGreater than or equal to
-ltLess than
-leLess than or equal to
-LikeMatch using the * wildcard character
-NotLikeDoes not match using the * wildcard character
-MatchMatches the specified regular expression
-NotMatchDoes not match the specified regular expression
-ContainsDetermines if a collection contains a specified value
-NotContainsDetermines if a collection does not contain a specific value
-InDetermines if a specified value is in a collection
-NotInDetermines if a specified value is not in a collection
Comparison Operator list from PS-101 Chapter 5 on Microsoft Learn

Using Operators to Compare Values

Most of these operators are similar to each other. PowerShell is generally case insensitive, because of its Windows-based origins. Operations on strings are case agnostic unless the case-sensitive operator (prefixed by “c”) is used.

PowerShell
$num1 = 10
$num1 -eq 10
PowerShell
'Hello' -eq 'hello'
'Hello' -ceq 'hello'

In PowerShell, lowercase letters are considered less than uppercase letters when you compare them.

-Like and -Match can confuse many people on how they evaluate. -like searches for a wildcard string, while -match uses regular expressions. For instanace, wildcards might catch everything before or after a string but RegEx can capture something more granular, like everything that contains a specific pattern of characters and symbols. It’s easier to see in practice. Check out an online regex builder like RegExr or RegEx101 if you want to dive into that.

PowerShell
$text = "The quick brown fox jumps over the lazy dog."
$pattern = "*b*"
$text -like $pattern
PowerShell
$text = "The quick brown fox jumps over the lazy dog."
$pattern = "\b[bB]\w+\b" # This matches any word starting with 'b' or 'B'
$text -match $pattern

Finally, -Contains and -In can be confusing. -Contains looks for a value in a collection of values, and -In looks for a collection in another value. This essentially looks for the same thing in different directions.

PowerShell
$cities = "New York", "Los Angeles", "Chicago", "Houston", "Philadelphia"
$cities -Contains 'New York'
PowerShell
$cities = "New York", "Los Angeles", "Chicago", "Houston", "Philadelphia"
"New York" -In $cities

The best use case for comparisons is for triggering conditional statements, which fire if something is true or false. We’ll cover that next.