Dos - Delete the oldest file using DIR /OD and EXIT

By xngo on March 9, 2019

The idea is to list all files by oldest date(DIR /OD) and then break out of the FOR loop on the 1st iteration using EXIT /B.

@ECHO OFF
SET FOLDER_PATH=%1
 
IF [%FOLDER_PATH%]==[] GOTO MISSING_ARGS
 
FOR /F "delims=" %%W IN ('dir /s/b/od %FOLDER_PATH%\*.rar') DO (
DEL /q %%W
EXIT /B 0
)
 
GOTO THE_END
:MISSING_ARGS
echo ERROR: FOLDER_PATH argument is missing! Supply FOLDER_PATH argument to the batch file.
 
:THE_END
@REM The end. Do nothing. There should be no other statement.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.