This batch file offers one solution:
@echo off
set "SourceFolder=C:\Temp"
for /F "skip=1 delims=" %%I in ('dir "%SourceFolder%\*" /A-D /B /O-D 2^>nul') do del "%SourceFolder%\%%I"
set "SourceFolder="
The command DIR outputs a list of just file names because of the options /A-D
(directory entries with directory attribute not set) and /B
(bare format) ordered reverse by last modification date because of /O-D
which means the name of the newest modified file is output first.
An error message output by DIR if the specified folder does not contain any file is suppressed by redirecting the error message written to handle STDERR to device NUL using 2>nul
. The redirection operator >
must be escaped here with caret character ^
to be interpreted as literal character on processing the entire FOR command line by Windows command interpreter. Later FOR executes in a separate command process in background the command dir "%SourceFolder%\*" /A-D /B /O-D 2>nul
and captures the output written to STDOUT.
FOR option skip=1
results in skipping first line of captured output which means ignoring the file name of newest modified file.
FOR option delims=
disables the default splitting up of the captured lines into space/tab separated strings as every entire file name should be assigned to loop variable I
for usage by command executed by FOR.
DEL deletes the file if that is possible at all.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
for /?
set /?
Read also the Microsoft article about Using Command Redirection Operators.