Powershell - LIKE against an array

2019-06-22 06:35发布

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

$excludeFiles = @"
aaa.bbb
ccccc.*
ddddd???.exe
"@ | SplitAndTrim;

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

$excludedFiles 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 -like 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?

3条回答
倾城 Initia
2楼-- · 2019-06-22 06:41

Here is a short version of the pattern in the accepted answer:

($your_array | %{"your_string" -like $_}) -contains $true

Applied to the case in the OP one obtains

PS C:\> ("aaa.bbb", "ccccc.*", "ddddd???.exe" | %{"ddddd000.exe" -like $_}) -contains $true
True
查看更多
爷的心禁止访问
3楼-- · 2019-06-22 06:45

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;
}
查看更多
一纸荒年 Trace。
4楼-- · 2019-06-22 06:49

I suppose you could use the Get-ChildItem -Exclude parameter:

Get-ChildItem $theFileToCheck -exclude $excludeFiles

If you have an array of files to check, Get-ChildItem accepts an array of paths:

Get-ChildItem $filesToCheck -exclude $excludeFiles
查看更多
登录 后发表回答