PowerShell: Use Get-ChildItem and Exclude Specific Items


By default, the Get-ChildItem cmdlet in PowerShell returns all files in a particular directory.

However, you can use the -Exclude operator to exclude files with specific extensions from being returned:

Get-ChildItem c:\users\bobbi\current_data -Recurse -Exclude *.csv, *.txt

This particular example will return all files in the directory that we specified except for the files that have .csv or .txt extensions.

By using the -Exclude operator, we are able to exclude files with specific extensions.

The following example shows how to use this syntax in practice.

Example: Use Get-ChildItem and Exclude Specific Items in PowerShell

Suppose we have a folder named current_data saved in the following location:

  • c:\users\bobbi\current_data

Suppose that we use the Get-ChildItem cmdlet to return all files in this directory:

Get-ChildItem c:\users\bobbi\current_data -Recurse

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

We can see that this 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 instead like to return all files but exclude the ones that have either .csv or .txt extensions.

We can use the following syntax to do so:

Get-ChildItem c:\users\bobbi\current_data -Recurse -Exclude *.csv, *.txt

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

PowerShell Get-ChildItem exclude specific items

Notice that all files are returned except for the ones that have .csv or .txt extensions.

Note: We chose to exclude two specific types of files, but you can include as many file extensions as you’d like after the –Exclude operator to exclude even more.

Related Tutorials

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

PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem with Multiple Filters
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to Use Get-ChildItem to Return Files Only

Leave a Reply