Kae Travis

Use PowerShell Comparison Operators to Compare Strings and Numbers

There are many instances where we need to use PowerShell comparison operators to compare strings and numbers. Here we go through some quick examples.

Comparing Strings with PowerShell

Here we use ‘eq’ to see if one string equals another. This is case-insensitive, meaning that the comparison ignores uppercase and lowercase characters. If we want a case-sensitive comparison, we use ‘ceq’.

A handy comparison operator is ‘like’ since we can use the asterisk as a wildcard to see if strings start with, end with or contain a certain other string of text.

#case insensitive comparison
write-host ("yesterday" -eq "yesterday")
#returns true
#case insensitive comparison
write-host ("yesterday" -eq "Yesterday")
#returns true
#case sensitive comparison
write-host ("yesterday" -ceq "Yesterday")
#returns false due to the upper case Y
#starts with 'yes'
write-host ("yesterday" -like "yes*")
#returns true
#ends with 'day'
write-host ("yesterday" -like "*day")
#returns true
#contains 'ter'
write-host ("yesterday" -like "*ter*")
#returns true

We can also do the inverse of the above, by comparing a string that is not equal to (-ne) or not like (-notlike) another string of text:

#case insensitive comparison
write-host ("yesterday" -ne "yesterday")
#returns false
#case insensitive comparison
write-host ("yesterday" -ne "Yesterday")
#returns false
#case sensitive comparison
write-host ("yesterday" -cne "Yesterday")
#returns true due to the upper case Y
#starts with 'yes'
write-host ("yesterday" -notlike "yes*")
#returns false
#ends with 'day'
write-host ("yesterday" -notlike "*day")
#returns false
#contains 'ter'
write-host ("yesterday" -notlike "*ter*")
#returns false

Comparing Numbers with PowerShell

When comparing numbers, a number is either equal to (-eq), greater than (-gt) or less than (-lt) another number.

write-host (1 -eq 1)
#returns true
write-host (2 -gt 1)
#returns true
write-host (1 -lt 2)
#returns true

Finally we can compare if a number is greater than or equal to (-ge) or less than or equal to (-le) another number like so:

write-host (1 -ge 1)
#returns true
write-host (2 -le 2)
#returns true
Use PowerShell Comparison Operators to Compare Strings and Numbers
Use PowerShell Comparison Operators to Compare Strings and Numbers

Leave a Reply