PowerShell: How to Use Case-Insensitive Contains()


By default, the Contains() method in PowerShell is case-insensitive.

However, you can use the ToLower() method in PowerShell to check if an object contains a specific string using case-insensitive matching:

$some_strings.ToLower().Contains("MY_STRING".ToLower())

This particular example checks if the string “MY_STRING” exists in the array of strings named $some_strings, using case-insensitive matching.

The following example shows how to use this syntax in practice.

Example: How to Use Case-Insensitive Contains() in PowerShell

Suppose we create the following array of strings in PowerShell named $teams:

$teams = @("Mavs", "Lakers", "Nuggets", "Warriors", "Kings")

Suppose we attempt to use the Contains() method with the following syntax to check if this array contains the string “LAKERS” or not:

$teams.Contains("LAKERS")

The following screenshot shows how to use this syntax in practice:

This returns False since the string “LAKERS” does not match any case of the team names in the $teams array.

To perform a case-insensitive Contains(), we must use the ToLower() method to first convert all strings in the array to lowercase and convert the string that we search for to lowercase as well:

$teams.ToLower().Contains("LAKERS".ToLower())

The following screenshot shows how to use this syntax in practice:

PowerShell case-insensitive Contains()

This returns True because the string “LAKERS” does exist in the array of team names, regardless of whether or not the case matches.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Concatenate Strings

Leave a Reply