CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Filtering Directory Contents When Using Regex with Get-ChildItem

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-08
powershell regex get-childitem PowerShell

I'm reviewing some code and I'm trying to filter the contents of a directory using `Get-ChildItem`, but I want to use a regex pattern to match file names that contain certain keywords. Specifically, I'm trying to find files that have 'report' or 'summary' in their names. However, when I run my command, it doesn't seem to apply the regex as expected and returns all files instead. Here’s the code I’m using: ```powershell $pattern = 'report|summary' Get-ChildItem -Path 'C:\Documents' | Where-Object { $_.Name -match $pattern } ``` I expected this to return only files with 'report' or 'summary' in the name, but I’m seeing every file in that directory. I’ve checked the regex syntax, and it seems correct. I also tried escaping the characters and using the `-Filter` parameter, but that didn't help either. Here’s the command with escaping: ```powershell $pattern = 'report|summary' Get-ChildItem -Path 'C:\Documents' -Filter '*report*' -or -Filter '*summary*' ``` This didn’t yield any results, either. Is there something I’m missing in terms of regex usage with `Get-ChildItem`? I also tried using `Select-String` to search within file content, but that isn’t what I need right now. Any suggestions would be greatly appreciated! I’m using PowerShell 7.3 on Windows 10. For context: I'm using Powershell on macOS. What am I doing wrong?