CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Difficulty Using `Get-ChildItem` with `-Recurse` and Excluding Specific File Types

πŸ‘€ Views: 786 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-24
powershell get-childitem file-management PowerShell

I'm upgrading from an older version and I'm a bit lost with I'm relatively new to this, so bear with me... I'm having trouble using `Get-ChildItem` to recursively list files in a directory, but I want to exclude certain file types, such as `.tmp` and `.log`. I tried using the `-Exclude` parameter, but it doesn't seem to work as expected when combined with `-Recurse`. Here’s what I’ve tried: ```powershell Get-ChildItem -Path 'C:\MyDirectory' -Recurse -Exclude '*.tmp', '*.log' ``` This command returns all files, including the ones I wanted to exclude. I also tried using the `-Filter` parameter: ```powershell Get-ChildItem -Path 'C:\MyDirectory' -Recurse -Filter '*.*' | Where-Object { $_.Extension -ne '.tmp' -and $_.Extension -ne '.log' } ``` While this works, it's not performant for large directories since it processes all files first and then filters them. I’d like to know if there's a more efficient way to achieve this without loading unnecessary files into memory. Is there a better approach in PowerShell 7.3 or is this simply a limitation of the `Get-ChildItem` cmdlet? How would you solve this? I'm coming from a different tech stack and learning Powershell. Am I approaching this the right way? Is there a better approach? I'm working with Powershell in a Docker container on Ubuntu 22.04.