PowerShell: Use Get-ChildItem with Multiple Filters


You can use the following syntax in PowerShell to use the Get-ChildItem cmdlet and apply multiple filters to only return files that have one of several specific extensions:

dir .\ -recurse | where {$_.extension -in ".xlsx",".csv"}

This particular example will return all of the files in the current directory that have one of the following file extensions:

  • .xlsx
  • .csv

The following examples show how to use this syntax in practice.

Example: Use Get-ChildItem with Multiple Filters in PowerShell

Suppose our current directory has the following path:

  • c:\users\bobbi\current_data

We can use the dir statement to view all files in this directory:

We can see that the directory contains the following files:

  • baseball_data.xlsx
  • basketball_data.xlsx
  • football_data.xlsx
  • hockey_data.xlsx
  • new_hockey_data.xlsx
  • pickleball_data.csv
  • player_data.txt
  • team_data.txt

Suppose that we would like to only return the files that have .xlsx or .csv as the extension.

We can use the following syntax to do so:

dir .\ -recurse | where {$_.extension -in ".xlsx",".csv"}

The following screenshot shows how to use this syntax in practice:

PowerShell Get-ChildItem multiple filters

Notice that this returns only the files that have .xlsx or .csv as the extension.

Note: We included two file extension types after the -in operator but you can include as many extensions as you’d like if you would like to filter for even more extensions.

Also note that we could instead use the -notin operator to exclude multiple file extensions from our results:

dir .\ -recurse | where {$_.extension -notin ".xlsx",".csv"}

The following screenshot shows how to use this syntax in practice:

Notice that this returns only the files that do not have .xlsx or .csv as the extension.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply