Reputation: 223
I'm having trouble getting my script to work correctly. I have three arrays. The extensions array does filter correctly. However my arrays with wildcards are not generating the results I want. What am I doing wrong?
# Read List of Servers from flat file
$data=Get-Content C:\myscripts\admin_servers.txt
# Variables that will be used against search parameter
$extensions = @(".ecc", ".exx", ".ezz", ".vvv")
$wildcards = @("Help_*.txt", "How_*.txt", "Recovery+*")
$exclude = @("help_text.txt", "Lxr*.exx", "help_contents.txt")
# Loop each server one by one and do the following
foreach ($server in $data)
{
# Search the server E:\ and all subdirectories for the following types of
# extensions or wildcards.
Get-ChildItem -path \\$server\e$ -Recurse | Where-Object {
(($extensions -contains $_.Extension) -or $_.Name -like $wildcards) -and
$_.Name -notlike $exclude
}
}
Upvotes: 2
Views: 508
Reputation: 7029
You could write your own function:
function Like-Any {
param (
[String]
$InputString,
[String[]]
$Patterns
)
foreach ($pattern in $Patterns) {
if ($InputString -like $pattern) {
return $true
}
}
$false
}
And then call it like this:
Get-ChildItem -path \\$server\e$ -Recurse |
Where-Object { `
(($extensions -contains $_.Extension) -or (Like-Any $_.Name $wildcards)) `
-and !(Like-Any $_.Name $exclude)}
Upvotes: 3
Reputation: 36342
If you are handy with Regular Expressions you can do this with a -Match
comparison. Replace your $Wildcards =
and $Exclude =
lines with:
$wildcards = "Help_.*?\.txt|How_.*?\.txt|Recovery\+.*"
$Exclude = "help_text\.txt|Lxr.*?\.exx|help_contents\.txt"
And then your Where-Object
line with:
Where-Object {(($extensions -contains $_.Extension) -or $_.Name -match $wildcards) -and $_.Name -notmatch $exclude}
That should do it for you. Explanation for the $Wildcard =
match available at this RegEx101 link.
Upvotes: 1