Neolisk Neolisk - 10 months ago 65
PowerShell Question

Powershell - LIKE against an array

For every file being processed, its name is being checked to satisfy the condition. For example, given the following list of filters:

$excludeFiles = @"
"@ | SplitAndTrim;

It should exclude a file from processing if it matches any of the lines. Trying to avoid
, because this script needs to be modifiable by someone who does not know it, and there are several places where it needs to implemented.

and similar are defined as a here-string on purpose. It allows the end user/operator to paste a bunch of file names right from the CMD/Powershell window.

It appears that Powershell does not accept
against an array, so I cannot write like this:

"ddddd000.exe" -like @("aaa.bbb", "ccccc.*", "ddddd???.exe")

Did I miss an option? If it's not natively supported by Powershell, what's the easiest way to implement it?


You can perform a pattern match against a collection of names, but not against a list of patterns. Try this:

foreach($pattern in $excludeFiles)
    if($fileName -like $pattern) {break}

Here is how it can be wrapped into a function:

function like($str,$patterns){
    foreach($pattern in $patterns) { if($str -like $pattern) { return $true; } }
    return $false;