One of my clients recently asked for a PowerShell script to find the most recent file in a directory. This might be something like grabbing the latest log file for troubleshooting, finding the most recent backup before running a script, or locating today’s report.
In this tutorial, I’ll walk you through three different methods for finding the most recent file using PowerShell. By the end, you’ll understand the pros and cons of each technique, know how to customize them for your specific needs, and have some practical examples you can use right away.
Method 1: The Simple One-Liner Method
Let’s start with the easiest approach. If you just need to quickly find the most recent file in a directory, this one-liner does the job beautifully:
Get-ChildItem -Path "C:\YourFolder" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1What’s happening here?
Get-ChildItemlists all items in the specified path (think of it like thedircommand, but far more powerful)-Fileensures we only get files, not foldersSort-Object LastWriteTime -Descendingsorts everything by the last modified time, newest firstSelect-Object -First 1grabs just the top result
This command returns a file object with all its properties — name, size, timestamps, and more. To see just the file path, you can add .FullName at the end:
(Get-ChildItem -Path "C:\YourFolder" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullNameHere is the script I executed in the screenshot below:
(Get-ChildItem -Path "C:\Bijay" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName
It displays the most recently modified file.
Pro Tip: Use LastWriteTime for the last time a file was modified, but if you need the most recently created file instead, use CreationTime. If you want the most recently accessed file, use LastAccessTime (though be aware that access times aren’t always reliably updated on all systems).
Check out Find Passwords in Files with PowerShell
Method 2: The Filtered Approach (When You Need Specific File Types)
In real-world scenarios, you often don’t want any file — you want the most recent *.log file, or the newest *.csv export, or the latest *.pdf report. Here’s how to add filtering to your search:
Get-ChildItem -Path "C:\Logs" -Filter "*.log" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1The -Filter parameter makes this incredibly efficient because it filters at the source rather than retrieving everything and then filtering. This makes a huge difference when working with directories containing thousands of files.
You can also use wildcards in creative ways:
# Find the most recent backup file
Get-ChildItem -Path "C:\Backups" -Filter "backup_*.zip" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1
# Find the most recent report for a specific month
Get-ChildItem -Path "C:\Reports" -Filter "*_January_*.xlsx" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1Common Pitfall: The -Filter parameter uses Windows wildcard syntax, which is slightly different from regex. If you need more complex pattern matching, use -Include or pipe to Where-Object instead — but be aware this is slower for large directories.
Check out How to Test If a File Exists in PowerShell?
Method 3: The Recursive Search (Finding Files Across Subdirectories)
Sometimes the file you need isn’t directly in the folder you’re looking at — it might be buried several levels deep in subdirectories. Adding the -Recurse parameter makes PowerShell search through all subdirectories:
Get-ChildItem -Path "C:\Projects" -Filter "*.docx" -File -Recurse | Sort-Object LastWriteTime -Descending | Select-Object -First 1This searches the entire folder tree under C:\Projects and returns the single most recent .docx file from anywhere within that structure.
Pro Tip: Recursive searches can take a while on large directory structures. If you’re working with network drives or folders with thousands of files, consider narrowing your search with specific filters or limiting the recursion depth with the -Depth parameter (available in PowerShell 5.1 and later):
Get-ChildItem -Path "C:\Projects" -Filter "*.docx" -File -Recurse -Depth 2This only searches two levels deep, which can dramatically speed things up.
Read PowerShell Get-ChildItem Files Only
Practical Examples
Now that you understand the methods, let’s look at some real-world scenarios where this becomes incredibly useful. Here are some practical examples I am sharing.
Example 1: Processing the Latest Log File
$latestLog = Get-ChildItem -Path "C:\Logs" -Filter "*.log" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Get-Content $latestLog.FullName -Tail 50This finds the most recent log file and displays the last 50 lines — perfect for quick troubleshooting.
Example 2: Backing Up Only the Newest File
$newestFile = Get-ChildItem -Path "C:\Reports" -Filter "*.xlsx" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Copy-Item $newestFile.FullName -Destination "C:\Backup\latest_report.xlsx"This automatically copies the most recent Excel report to a backup location with a standard name.
Example 3: Finding Files Modified Today
$today = Get-Date -Hour 0 -Minute 0 -Second 0
$newestToday = Get-ChildItem -Path "C:\Data" -File | Where-Object {$_.LastWriteTime -ge $today} | Sort-Object LastWriteTime -Descending | Select-Object -First 1This finds the most recent file that was modified today, specifically.
Check out How to List Hidden Files in PowerShell?
Best Practices and Advanced Tips
1. Store Results in Variables for Multiple Uses
If you need to work with the file multiple times, store it in a variable:
$latestFile = Get-ChildItem -Path "C:\Folder" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Write-Host "Found: $($latestFile.Name)"
Write-Host "Size: $($latestFile.Length) bytes"
Write-Host "Modified: $($latestFile.LastWriteTime)"2. Handle Cases Where No Files Exist
Always check if files were actually found before trying to use them:
$latestFile = Get-ChildItem -Path "C:\Folder" -Filter "*.txt" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($latestFile) {
Write-Host "Found: $($latestFile.FullName)"
} else {
Write-Host "No matching files found!"
}3. Compare Multiple Files
Want to find the three most recent files instead of just one? Simply change -First 1 to -First 3:
Get-ChildItem -Path "C:\Folder" -File | Sort-Object LastWriteTime -Descending | Select-Object -First 34. Use Aliases for Shorter Scripts
In my experience, when writing quick interactive commands, PowerShell’s aliases make life easier. Get-ChildItem can be shortened to gci or even ls or dir:
gci "C:\Folder" -File | sort LastWriteTime -Descending | select -First 1However, for scripts that others will read or maintain, I always recommend using full cmdlet names for clarity.
Common Caveat: Be careful with file systems that don’t preserve timestamps accurately, particularly when copying files from certain network sources or cloud storage. Sometimes the “modified” time gets updated during transfer, which can throw off your results.
Wrapping Up
In this tutorial, I explained various methods to find the most recent file in a directory using PowerShell. We checked methods such as a simple one-liner for quick checks, adding filters for specific file types, or doing recursive searches across directory trees.
You may also like the following tutorials:
- Get Files Older Than 1 Month with PowerShell
- Find Files Modified After a Specific Date Using PowerShell
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.