How do I find the most recently created file in a directory from a batch file?
We’ve reached Hump Day of Batch File Week. Remember, nobody actually likes batch programming. You merely tolerate it.
Today, we’ll find the most recently-created item in a directory. (For example, we have a server that holds our daily builds, and you might want to write a batch file that automatically installs the latest build.)
There may be better ways, but what I do is ask for a list sorted oldest-to-newest, and then choose the last one.
for /f %%i in ('dir /b/a-d/od/t:c') do set LAST=%%i echo The most recently created file is %LAST%
This trick works by asking the
to list just the names (
of just the files
sorted by date (
based on the creation time (
Each time a new file is reported,
its name is stored in the
overwriting the previous one.
When the loop finishes,
LAST variable contains the name of the
since that’s the one that didn’t get overwritten.
You can tweak the command line to perform other queries.
For example, if you want the newest file, then just ask
for a reverse sort (
If you want the file sorted by modified time rather than
You get the idea.
Limitations: The implementation above assumes that no files contain spaces in their name. Removing this limitation is left as an exercise.