Reputation: 19217
I have just started using PowerShell today, and I have an intention list files by a few patterns in an array, for instance:
$matchPattern = (
"SomeCompany.SaaS.Core.Mvc*",
"SomeCompany.SaaS.Core.UI.Framework*"
);
I want to list files in a $sourceDir
where any of the item in the above array matches.
I can do this, and it works:
foreach ($item in $matchPattern)
{
Get-ChildItem $sourceDir | Where-Object {$_.Name -like $item}
}
Just for learning purposes, can I do it in pipe-lining?
Something similar to this:
Get-ChildItem $sourceDir | Where-Object { $matchPattern -contains $_.Name }
Upvotes: 5
Views: 7624
Reputation: 2621
Something like this should work.
Assuming an array $a exists with some strings in it:
gci $someDir | %{$a -eq $_.name}
Whenever the name of the directory found by gci matches a value in the $a array, it will echo out that value. So if $someDir=C:\ and "windows" was an element in $a, the output would be just "windows" if it was the only match.
Edit: My mistake, I did not realize you wanted the * as a wildcard and not a literal, this only matches literals. Solved below.
For pattern matches, you can use regex arrays. Define one like so
[regex]$patt = “^(Win.*|.*Files)$”
You can now compare all matches like the above
gci $someDir | ?{$_.name -match $patt}
Upvotes: 0