PowerShell: Use Get-ChildItem and Limit Number of Results


When using the Get-ChildItem cmdlet in PowerShell, you may sometimes want to limit the number of results that are returned.

You can use the following methods to do so:

Method 1: Use Get-ChildItem and Limit to N Top Files

Get-ChildItem | Select -First 5

This particular example will return only the first 5 files from the current directory.

Method 2: Use Get-ChildItem and Limit to N Most Recently Modified Files

Get-ChildItem | Sort LastWriteTime -Descending | Select -First 5

This particular example will return only the 5 most recently modified files from the current directory.

The following examples show how to use each method in practice with a directory that contains the following files:

Example 1: Use Get-ChildItem and Limit to N Top Files

We can use the following syntax with the Get-ChildItem cmdlet to return only the top 5 files in the current directory:

Get-ChildItem | Select -First 5

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

PowerShell Get-ChildItem limit to N results

Notice that this only returns the top 5 files from the current directory.

Feel free to change 5 to a different number to instead return a different number of files.

Example 2: Use Get-ChildItem and Limit to N Most Recently Modified Files

We can use the following syntax with the Get-ChildItem cmdlet to return only the 5 most recently modified files in the current directory:

Get-ChildItem | Sort LastWriteTime -Descending | Select -First 5

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

Notice that this returns only the 5 most recently modified files in the current directory.

Feel free to change 5 to a different number.

For example, you could use -First 1 to return only the most recently modified file in the current directory.

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