How to find the oldest file in given directory in Windows CMD?
8,712
got it....
@echo on
setlocal EnableDelayedExpansion
forfiles -p "sourcePath" -s -m *.* /D -7 /C "cmd /c del @path" >> log/log.txt
it's delete all files older then 7 days ago
Related videos on Youtube
Author by
Tzahi Kadosh
Updated on September 18, 2022Comments
-
Tzahi Kadosh almost 2 years
I'm trying to delete the oldest file in a given path VIA batch file.
My code:@echo on setlocal EnableDelayedExpansion set source = C:\Users\tzahi.k\Desktop\scripts\testSource\source for /F "delims=" %%a in ('dir %source% /a-d /b /o-d ') do set oldest=%%a >> del_oldest_log.txt
This chooses every file in the folder.
What am I doing wrong?
Help :-)-
Dude named Ben almost 8 yearsHave a look at this answer.
-
-
user1016274 almost 8 yearsThat's not what you've asked for (but it may work for you). The linked post offers the correct solution. In your
for
loop, the last (and oldest) output will overwrite younger entries. Just assign it in the loop, then after the loopecho
it to the logfile and use it to delete the oldest file. Or sort oldest files first, and leave the loop logging and deleting with angoto
.