You can use the following syntax in PowerShell to get the most recently modified file in a directory:
ls | Sort-Object -Descending -Property LastWriteTime | Select -First 1
This particular example will list the most recently modified file in the current directory.
Note: If you would instead like to get the file that was modified the longest time ago, you can uses the -Last operator instead of the -First operator.
The following example shows how to use this syntax in practice.
Example: How to Get Most Recently Modified File in Directory 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:

Suppose that we we would like to get the file in the directory that was modified most recently.
We can use the following syntax to do so:
ls | Sort-Object -Descending -Property LastWriteTime | Select -First 1
The following screenshot shows how to use this syntax in practice:

We can see that the file named new_data.txt was modified most recently in this directory.
We can see that it has a LastWriteTime property of 2/23/2024 10:40 AM.
If we would instead like to get the file that was modified least recently, then we can use the following syntax:
ls | Sort-Object -Descending -Property LastWriteTime | Select -Last 1
The following screenshot shows how to use this syntax in practice:

We can see that the file named my_data.txt was modified least recently in this directory.
We can see that it has a LastWriteTime property of 9/9/2022 9:03 AM.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
