Powershell包含-是否匹配部分字符串和列表?

问题描述 投票:2回答:1

我的脚本中有这种情况:

$Excludes = "Commvault","Veeam"

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

这是最有效的测试方法,还是有一种更快的方法来将用户与每个排除的单词匹配?

powershell match contains
1个回答
0
投票

如何,使用正则表达式搜索组

$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 " }
© www.soinside.com 2019 - 2024. All rights reserved.