I like to search some old files with predefined extensions. (like .doc,.xls,.txt etc.) in a specific folder. I put the extensions in a variable:
$wildcards = @(".txt",".doc",".xls")
When I put a new value in this variable it has to change another variable. ($collection)
Here is my code:
$folder = Get-ChildItem C:\test\test1\
$date = (Get-Date).Add(-1)
$wildcards = @(".txt",".doc",".xls")
function Get-WildCards {
$counter = 0;
$counterEnd = $wildcards.Count
$collection = New-Object System.Collections.ArrayList
$filter = "$" + "_.Extension" + " -like $" + "wildcards[" + $counter + "]}"
$or = " -or "
for ($counter = 0; $counter -lt $counterEnd; $counter++) {
$filter = "$" + "_.Extension" + " -like $" + "wildcards[" + $counter + "]}"
$collection += $filter + $or
}
$collection = [String]::Join('', $collection)
$collection = $collection.ToString()
$collection = $collection.TrimEnd($or)
}
Get-WildCards
$folderPath = $folder.FullName
$files = Get-ChildItem -Path $folderPath -File:$true |
Where-Object {$collection}
$files
If I run this code the Where-Object condition won't work this way. It won't filter the extensions. How can I achieve that it works? Any helps appreciated.
You seem to be complicating things. Try this -
$folder = Get-ChildItem C:\test\test1\
$wildcards = @(".txt",".doc",".xls")
$files = Get-ChildItem -Path $folderPath | where {$_.extension -in $wildcards}
$files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With