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

3 1

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.

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute and it's free.

Get started

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay