Batch File – Get Directory Named with Latest Date

batchbatch-filebatch-processing

I have a directory with many subdirectories. Each subdirectory is named with the yyyy-mm-dd format. I'm writing a Windows batch file and I need to grab the directory name with the most recent date and put that string into a variable. The last modified dates were changed, so using the last modified timestamp isn't an option.

Can anyone point me in the right direction?

Best Answer

for /f %%d in ('dir /ad /o-n /b .') do (
  echo %%d
  goto break
)
:break
  • /ad - Displays files with specified attributes. (D: Directories)
  • /o-n List by files in sorted order. (n: By name (alphabetic), -n: Prefix to - reverse order)
  • /b Uses bare format (no heading information or summary).
  • goto break - jump out the loop to take only first

ps

  • /o-d List by files in sorted order. (d: By date/time (oldest first), -d: Prefix to - reverse order)