PowerShell: Check if String Exists in List of Strings


You can use the following syntax in PowerShell to check if a specific string exists in a list of strings:

$list_of_strings -contains "this_string"

This particular example checks if the string “this_string” exists in the variable named list_of_strings.

This statement will either return True or False.

The following examples show how to use this syntax in practice.

Example: How to Use “If Like” in PowerShell

Suppose we have a variable named teams that contains the following list of strings:

  • “Mavs”, “Lakers”, “Nuggets”, “Warriors”, “Kings”

Suppose that we would like to check if this list of strings contains the string “Warriors” anywhere in it.

We can use the following syntax to do so:

$teams = "Mavs", "Lakers", "Nuggets", "Warriors", "Kings"
$teams -contains "Warriors" 

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

PowerShell check if string exists in list of strings

The statement returns True because the string “Warriors” does indeed belong in the list of strings.

It’s worth noting that the -contains operator is not case-sensitive.

For example, suppose we check if the string “WARRIORS” exists in the list of strings:

The statement returns True because the string “WARRIORS ” (regardless of cases) does belong in the list of strings.

It’s also worth nothing that the -contains operator looks for an exact match.

For example, suppose we search for the substring “Warr” instead:

The statement returns False because the exact string “Warr” does not belong in the list of strings.

Related Tutorials

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

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply