Powershell - LIKE vs. array

For each file being processed, its name is checked to satisfy the condition. For example, given the following filter list:

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

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

$excludedFiles and the like are generally defined as a whole line. This allows the end user / operator to embed a bunch of file names directly from the CMD / Powershell window.

Powershell doesn't seem to accept -like against an array, so I can't write like this:

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

Did I miss an option? If this is not supported by Powershell, what is the easiest way to implement it?

+5
source share
4 answers

You can match patterns to a collection of names, but not against a list of patterns. Try the following:

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

Here's how to wrap it in a function:

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

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

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

In relation to the case in OP it turns out

 PS C:\> ("aaa.bbb", "ccccc.*", "ddddd???.exe" | %{"ddddd000.exe" -like $_}) -contains $true True 
+6
source

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

 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 
+1
source

$ excludeFiles.Where {$ stringToTest -like $ _}

The Powershell array has a Where method, which can accept the input of an expression, hence {} instead of (). Enter a string to check, and it will iterate over the array using the standard channel, so $ _ represents an element of the array.

Displays a list of matching items.

 PS H:\> $excludeFiles = @("aaa.bbb", "ccccc.*", "ddddd???.exe") PS H:\> $stringToTest = "ddddd000.exe" PS H:\> $excludeFiles.Where{$stringToTest -like $_} ddddd???.exe 
0
source

Source: https://habr.com/ru/post/1441381/


All Articles