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.
When you would like to see if two strings are exactly the same, you can make use of the equals operator.
You can use
-eq to perform a case-insensitive string comparison.
❯ "Ivan Kahl's Blog" -eq "ivan kahl's BLOG" True
If you would like to do a case-sensitive string comparison, you can use
❯ "Ivan Kahl's Blog" -ceq "ivan kahl's BLOG" False
You can also use patterns for string comparisons using the Like operator in Powershell.
If you want to use a pattern for string comparison and not worry about the case, use
❯ "Ivan Kahl's Blog" -like "ivan kahl's*" True
If you do want to check case while using string patterns, you can make use of
❯ "Ivan Kahl's Blog" -clike "ivan kahl's*" False
I hope you found this quick tip useful. If you have any questions or thoughts, please leave a comment below.