PowerShell: How to List Files in Directory by Date


You can use the following syntax in PowerShell to list all files in a directory in order by last accessed date:

ls | sort LastAccessTime -Descending

This particular example will list out all file names in the current directory in order by last accessed date.

Note: The most recently accessed file will appear first in the list of file names.

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

Example: How to List Files in Directory by Date Using PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\OneDrive\Documents\test_data

We can type Dir to list out all files in this current directory:

By default, the files are currently listed in alphabetical order from A to Z.

Suppose that we we would instead like to list out all file names based on their last accessed date.

We can use the following syntax to do so:

ls | sort LastAccessTime -Descending

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

PowerShell list files in order by date

We can see that the files are now listed in order based on when they were last accessed.

We can see that new_data.txt was accessed most recently, then that_data.txt, then cool_data.xlsx, and so on.

If you have a huge number of files in one directory and you only want to view the n most recently accessed files, then you can use the -First operator.

For example, we can use the following syntax to list only the three most recently accessed files:

ls | sort LastAccessTime -Descending | Select-Object -First 3

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

We can see that only the three most recently accessed files are listed in order.

Note: Feel free to change the numeric value after the -First operator to display as many files as you’d like.

Related Tutorials

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

PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to List All Files in Directory to Text File

Leave a Reply