DEV Community

Cover image for Case-sensitive and Case-insensitive String Comparisons in PowerShell
Ivan Kahl
Ivan Kahl

Posted on • Originally published at blog.ivankahl.com

Case-sensitive and Case-insensitive String Comparisons in PowerShell

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 exactly 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Case-Sensitive Like (-clike)

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

 "Ivan Kahl's Blog" -clike "ivan kahl's*"
False
Enter fullscreen mode Exit fullscreen mode

Closing

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

Latest comments (0)