PowerShell – How to Check if String Contains Any Value in Array

Very short post today, the PowerShell script below is simply a function that will take a string such as “Red fox jumping over fences” and will compare it to an array of values to see if it contains any of them.

# Set the variables
$description = "Red fox jumping over fences"
$searchArray = @("fox", "red", "blue")

# Simple function to check if a string contains any one of a set of terms to search for
# Returns True if found or False otherwise
function containsArrayValue {
    param ( 
        [Parameter(Mandatory=$True)]
        [string]$description,

        [Parameter(Mandatory=$True)]
        [array]$searchTerms
    )

    foreach($searchTerm in $searchTerms) {
        if($description -like "*$($searchTerm)*") {
            return $true;
        }
    }

    return $false;
}

# Call the function
containsArrayValue $description $searchArray

and finally, the output –


Try Cartel Empire today. A completely free, persistent-MMO developed by me.

2 thoughts on “PowerShell – How to Check if String Contains Any Value in Array

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.