Inside a folder (say c:\test) I want to delete the oldest file if the number of files are over 21.
This is what I came up with, issue is that it one time deletes the oldest file, second run it does nothing and deletes the oldest for third, continues like that. Also it doesn’t care if the file amount is lower than 21, deletes even if it is lower.
Here is the code:
SET BACKUPDIR=C:\test
SET countfiles=dir BACKUPDIR /b | find /v /c "::"
if countfiles GTR 21 (
FOR /F %%i IN ('DIR /B /O-D %BACKUPDIR%') DO SET OLDEST=%%i
DEL %BACKUPDIR%\%OLDEST%
)
here’s an alternative in vbscript, that iterates the directory just once.
save as deletefile.vbs and on command line