PowerShell: How to Get First File that Matches a Pattern


Often you may want to use PowerShell to get the first file in a folder that matches a specific pattern.

You can use the following syntax to do so:

Get-ChildItem -File -Filter *.csv | Select-Object -First 1

This particular example will return the first file from the current directory that ends in the pattern .csv.

Here is what the various commands do:

  • Get-ChildItem -File: Retrieve all files in current directory.
  • -Filter *.csv: Filters for only the files that contain .csv as the extension.
  • Select-Object -First 1: Specifies that only the first file should be returned.

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

Example: Use PowerShell to Get First File that Matches a Pattern

We can use the Dir command to first view all files in our current directory:

We can see that our current directory has six total files.

Suppose that we would like to retrieve the first file in the folder that contains .csv as the file extension.

We can use the following syntax to do so:

Get-ChildItem -File -Filter *.csv | Select-Object -First 1 

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

PowerShell get first file that matches pattern

Notice that this returns the first file from the folder that contains .csv as the file extension.

Note that if you’d like to return only the filename itself then you can use the Name property:

(Get-ChildItem -File -Filter *.csv | Select-Object -First 1).Name

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

Notice that this returns only the first filename (player_data.csv) from the folder that contains .csv as the file extension.

Note: Feel free to change *.csv to any other pattern that you would like to match.

Related Tutorials

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

PowerShell: How to Get First Filename from a Folder
PowerShell: How to Get File Name from Path
PowerShell: How to Add Date to File Name
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply