Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering file extensions with Powershell

Tags:

powershell

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.

like image 519
wolfnlight Avatar asked Oct 26 '25 10:10

wolfnlight


1 Answers

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
like image 173
Vivek Kumar Singh Avatar answered Oct 29 '25 06:10

Vivek Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!