PowerShell: Check if String Contains any Substring from Array

You can use the following syntax in PowerShell to check if a string contains any substring from an array:

($list_of_substrings | % {$string.contains($_)}) -contains $true

This particular example checks if the string variable named $string contains any of the substrings in the array named $list_of_substrings.

Here is how this syntax works:

First, we pipe ( | ) the $list_of_substrings array into a foreach loop ( % ) and check if each substring in the array exists in the $string variable.

This returns a list of True and False values to indicate if each substring exists in the array or not.

Lastly, we use -contains $true to check if any of the values returned True, which would indicate that at least one substring exists in the array.

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

Example: Check if String Contains any Substring from Array in PowerShell

Suppose we have an array named $list_of_substrings that contains the names of various basketball teams.

Suppose we also have a string variable named $string that contains a string with information about our favorite basketball team.

We can use the following syntax to check if $string contains any substring from $list_of_substrings:

$string = 'My favorite team is the Nets'
$list_of_substrings = @('Mavs', 'Nets', 'Kings')

($list_of_substrings | % {$string.contains($_)}) -contains $true

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

PowerShell check if string contains substring from array

The statement returns True because the string does indeed contain at least one substring (‘Nets’) from the array of substrings.

Note: You can find the complete documentation for the contains operator in PowerShell here.

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