How do I find the most recently created file in a directory from a batch file?

Raymond Chen

Raymond

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 dir command to list just the names (/b) of just the files /a-d, sorted by date (/od), based on the creation time (/t:c).

Each time a new file is reported, its name is stored in the LAST variable, overwriting the previous one. When the loop finishes, the LAST variable contains the name of the newest file, 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 (/o-d). If you want the file sorted by modified time rather than creation time, then use /t:w. 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.

0 comments

Comments are closed. Login to edit/delete your existing comments