Powershell contains - match on partial string and list?

Viewed 1023

I have this situation in my script:

$Excludes = "Commvault","Veeam"

$testuser = 'DOMAIN\vCommvaultConnect'
$Excludes | ForEach-Object {
    If ($testuser.Contains($_)) {
    Write-Host "Found"
    }
}

Is this the most efficient way to test for this or is there a faster way to match a user to each of those excluded words?

1 Answers

How about this, using Regex search groups

$Excludes = "Commvault","Veeam"

$SearchRegex_Excludes = ($Excludes | % { "(" + ($_) + ")" }) -join "|"
# sample regex pattern result - (Commvault)|(Veeam)

$testuser = "DOMAIN\vCommvaultConnect"

if ( $testuser -match $SearchRegex_Excludes ) { "Found" } else { "Not Found " }
Related