Batch file deletes all but the newest 10 files
The batch file has the following:
:REMOLDFILES
ECHO Removing files older than 14 days. >>%LOGFILE%
cd /d %BKUPDIR%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.zip ^2^>nul') DO IF EXIST "%%~fA" ECHO "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.zip ^2^>nul') DO IF EXIST "%%~fA" DEL "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.log ^2^>nul') DO IF EXIST "%%~fA" ECHO "%%~fA" >>%LOGFILE%
FOR /f "skip=14 delims=" %%A IN ('DIR /a:-d /b /o:-d /t:c %1*.log ^2^>nul') DO IF EXIST "%%~fA" DEL "%%~fA" >>%LOGFILE%
IF [%3]==[Y] GOTO SECONDBACKUPDIR
IF [%3]==[y] GOTO SECONDBACKUPDIR
GOTO END
The problem I ran into was that the backup didn't run for a couple of weeks and ended up deleting all of my backups as they were over 2 weeks old.
I need to keep the last 10 most recent backups.
Anyone have an idea how I would go about this? I didn't write this once as I am not familiar with batch files.
source to share
You can list files in reverse order by modification date using the command DIR
. Then you just tell your loop FOR
to skip the first 10 ( note ) where your zip is showing 14
but you are asking for 10) records, so all processed ones are deleted.
REM Update to 14 if needed.
SET Keep=10
FOR /F "usebackq tokens=* skip=%Keep% delims=" %%A IN (`DIR *.zip /B /O:-D /A:-D`) DO DEL "%%A">>%LOGFILE%
Since you are not familiar with the package, you can test this command (to see what will be removed, not remove it) by replacing it DEL
with ECHO
.
Edit
Since you are also processing log files, why not just delete them in one cycle?
REM Update to 14 if needed.
SET Keep=10
FOR /F "usebackq tokens=* skip=%Keep% delims=" %%A IN (`DIR *.zip /B /O:-D /A:-D`) DO (
ECHO Processing: %%~nA
REM Delete ZIP file.
DEL "%%A"
REM Delete LOG file.
DEL "%%~nA.log"
)>>%LOGFILE%
source to share