PowerShell: How to Get First Filename from a Folder


Often you may want to use PowerShell to get only the first file from a folder.

You can use the following syntax to do so:

Get-ChildItem -File | Select-Object -First 1

This particular example will return the first filename from the current directory.

Here is what the various commands do:

  • Get-ChildItem -File: Retrieve all files in current directory
  • Select-Object -First 1: Specifies that only the first file should be returned

Note that you can use -First N to instead return the first N files from a folder if you would like.

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

Example: Use PowerShell to Get First Filename from a Folder

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 only the first file.

We can use the following syntax to do so:

Get-ChildItem -File | Select-Object -First 1 

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

PowerShell get first file in folder

Notice that this returns only the first file from the folder.

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

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

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

PowerShell get first filename in folder

Notice that this returns only the first filename (athletes.txt) from the folder.

Related Tutorials

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

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