Case-sensitive and Case-insensitive String Comparisons in PowerShell

Discover how to perform case-sensitive and case-insensitive string comparisons in PowerShell. This article explains using operators like -eq, -ceq, -like, and -clike for precise string handling.

I wrote a PowerShell script the other day and, while doing so, discovered an interesting fact about string comparison in PowerShell that is quite contrary to .NET (and thus unfamiliar for me): string comparisons are case-insensitive by default.

This caught me off-guard since my particular use case required a case-sensitive comparison. I managed to get case-sensitive comparisons to work and thought I'd share it.

Using the Equals operator (-eq/-ceq)

When you would like to see if two strings are the same, you can make use of the equals operator.

Case-Insensitive Equals (-eq)

You can use -eq to perform a case-insensitive string comparison.

❯ "Ivan Kahl's Blog" -eq "ivan kahl's BLOG"
True

Case-Sensitive Equals (-ceq)

If you would like to do a case-sensitive string comparison, you can use -ceq:

❯ "Ivan Kahl's Blog" -ceq "ivan kahl's BLOG"
False

Using the Like operator (-like/-clike)

You can also use patterns for string comparisons using the Like operator in Powershell.

Case-Insensitive Like (-like)

If you want to use a pattern for string comparison and not worry about the case, use -like:

❯ "Ivan Kahl's Blog" -like "ivan kahl's*"
True

Case-Sensitive Like (-clike)

If you do want to check the case while using string patterns, you can make use of -clike:

❯ "Ivan Kahl's BLog" -clike "ivan kahl's*"
False

Closing

I hope you found this quick tip useful. If you have any questions or thoughts, please leave a comment below.