CodexBloom - Programming Q&A Platform

PowerShell 7.3 - how to to Filter Files with Specific Extension Recursively in a Directory

๐Ÿ‘€ Views: 66 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
powershell file-filtering get-childitem PowerShell

I'm prototyping a solution and I'm refactoring my project and I've searched everywhere and can't find a clear answer. I'm relatively new to this, so bear with me... I'm currently working on a PowerShell script to search for and filter specific file types in a directory and its subdirectories. I'm trying to find all `.txt` files that are larger than 1 MB, but I'm running into issues with the filtering. Hereโ€™s what Iโ€™ve been using: ```powershell $path = 'C:\MyDirectory' $files = Get-ChildItem -Path $path -Recurse | Where-Object { $_.Extension -eq '.txt' -and $_.Length -gt 1MB } ``` When I run this script, it returns no results even though I know there are `.txt` files over 1 MB in that directory. I've also tried checking the directory manually and confirmed that the files exist and meet the size requirement. I thought maybe the question was with the `-Recurse` parameter, so I tried running `Get-ChildItem` without it and it correctly returns the files in the top-level directory, but still doesn't work when searching recursively. I also attempted to use `-File` in `Get-ChildItem` to ensure I'm only getting files, but that didnโ€™t change the outcome: ```powershell $files = Get-ChildItem -Path $path -Recurse -File | Where-Object { $_.Extension -eq '.txt' -and $_.Length -gt 1MB } ``` Still no luck. Is there something I'm missing in my command, or is there a known scenario with filtering these specific conditions in PowerShell 7.3? Any help would be greatly appreciated! For context: I'm using Powershell on Windows. Any help would be greatly appreciated! Thanks, I really appreciate it! Is there a simpler solution I'm overlooking? I'd really appreciate any guidance on this.