PowerShell: How to Use Get-ChildItem with Filter


You can use the following syntax in PowerShell to use the Get-ChildItem cmdlet with the Filter operator to only retrieve files in a folder that match some filter criteria:

$hockey_files = Get-ChildItem -Path $path -Filter "*hockey*.xlsx" -Recurse

This particular example will get all of the Excel files that contain hockey in the file name within the folder specified in the location by the $path variable.

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

Example: How to Use Get-ChildItem with Filter in PowerShell

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

  • c:\users\bobbi\current_data

We can use the following syntax to view each of the files in this folder:

$path = "c:\users\bobbi\current_data"
Dir $path

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

We can see that the folder contains the following five Excel files:

  • baseball_data.xlsx
  • basketball_data.xlsx
  • football_data.xlsx
  • hockey_data.xlsx
  • new_hockey_data.xlsx

Suppose that we would like to filter for only the files that contain hockey in the file name.

We can use the following syntax to do so:

$hockey_files = Get-ChildItem -Path $path -Filter "*hockey*.xlsx" -Recurse

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

PowerShell Get-ChildItem filter

Notice that the new variable named $hockey_files only contains the files from the folder that contain hockey in the name:

  • hockey_data.xlsx
  • new_hockey_data.xlsx

Note that we used asterisks ( * ) as wildcard characters around hockey when using the -Filter operator to specify that we would like to return all file names that contain the string “hockey” with any characters before or after the string.

Feel free to replace “hockey” with whatever string you would like to filter using a different string.

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