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 responses to “PowerShell – How to Check if String Contains Any Value in Array”

  1. Clem Avatar
    Clem

    You have a typo in your code. thanks for the info.
    foreach($searchTerm in $searchterms) —-searchterms should be searchTerms

    Liked by 1 person

    1. shaun.wilkinson Avatar

      So I did, thank you for getting in touch and I’ve updated the post.

      Like

Leave a comment

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

Design a site like this with WordPress.com
Get started