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 Operator | Definition |
---|---|
-eq | Equal to |
-ne | Not equal to |
-gt | Greater than |
-ge | Greater than or equal to |
-lt | Less than |
-le | Less than or equal to |
-Like | Match using the * wildcard character |
-NotLike | Does not match using the * wildcard character |
-Match | Matches the specified regular expression |
-NotMatch | Does not match the specified regular expression |
-Contains | Determines if a collection contains a specified value |
-NotContains | Determines if a collection does not contain a specific value |
-In | Determines if a specified value is in a collection |
-NotIn | Determines if a specified value is not in a collection |
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.
$num1 = 10
$num1 -eq 10
'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.
$text = "The quick brown fox jumps over the lazy dog."
$pattern = "*b*"
$text -like $pattern
$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.
$cities = "New York", "Los Angeles", "Chicago", "Houston", "Philadelphia"
$cities -Contains 'New York'
$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.