PowerShell - 如何检查字符串以查看它是否包含带通配符的另一个字符串?

时间:2015-10-01 20:16:37

标签: string powershell for-loop pattern-matching wildcard

我想查看文件列表并检查每个文件名是否与列表中的任何字符串匹配。这是我到目前为止,但没有找到任何匹配。我做错了什么?

$files = $("MyApp.Tests.dll","MyApp.Tests.pdb","MyApp.dll")
$excludeTypes = $("*.Tests.dll","*.Tests.pdb")

foreach ($file in $files) 
{
    $containsString = foreach ($type in $ExcludeTypes) { $file | %($_ -match '$type') }

    if($containsString -contains $true)
    {
        Write-Host "$file contains string."
    }
    else
    {
        Write-Host "$file does NOT contains string."
    }
}

1 个答案:

答案 0 :(得分:0)

使用通配符时,您希望使用-like运算符而不是-match运算符,因为后者需要正则表达式。例如:

$files = @("MyApp.Tests.dll","MyApp.Tests.pdb","MyApp.dll")
$excludeTypes = @("*.Tests.dll","*.Tests.pdb")

foreach ($file in $files) {
    foreach ($type in $excludeTypes) {
        if ($file -like $type) { 
            Write-Host ("Match found: {0} matches {1}" -f $file, $type)
        }
    }
}