SoFunction
Updated on 2025-03-04

Implementation code for filtering by file suffix in PowerShell

When using PowerShell, the editor often uses Get-ChildItem (aliased as dir) to get some files or directories. Then filter these results by file type, that is, file suffix. Many times after doing such a job, I feel annoyed. Is there any simple, once and for all? Let’s discuss it today.

I won't keep it aside, give me a Filter code first, let's take a look:

Copy the codeThe code is as follows:

Filter Where-Extension
{
   param
   (
       [String[]]
       $extension = ('.png', '.jpg', '.gif')
   )
  
   $_ |
   Where-Object {
       $extension -contains $_.Extension
   }
}

What is Filter? Let's put it this way, it's similar to a function, but it's placed behind a pipeline. So you will see a mark like "$_ |" in Filter. This Filter requires an array parameter to be passed, that is, the suffix list. If you do not pass it, then by default, filter .png, .jpg and .gif.
OK, let's see how to use it.

I want to filter all text files such as .txt or .log in the root directory of the d disk, and write the PowerShell script like this:

Copy the codeThe code is as follows:

dir d:\ | Where-Extension .txt,.log

You can tell me about this Filter in the profile so that you can use it directly without defining it every time you call it. ah? You don't know what a profile is? Then go and have a lookThis articleBar.