Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - How to check a string to see if it contains another string with wildcard?

I want to go through a list of files and check if each filename match any of the string in a list. This is what I have so far, but it is not finding any match. What am I doing wrong?

$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."
    }
}
like image 876
TNV Avatar asked Dec 20 '25 01:12

TNV


1 Answers

With wildcards you want to use -like operator instead of -match because the latter requires a regular expression. Example:

$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)
        }
    }
}
like image 157
Alexander Obersht Avatar answered Dec 23 '25 00:12

Alexander Obersht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!