I created a batch file with the objective of thinning out older backup files. More specifically, the script identifies backup files with a last modified date of between 183 and 365 days old, deleting all bar one file for each 7 day period within the overall 6 month period. If there are zero or one file for the 7 day period then no files are deleted.
The script basically works but relies on a temporary file for storing the filenames of the matched files for each 7 day period. I want to know if the script can be modified to do the same without the need for a temporary file.
The script takes inspiration from a technique described in aschipfl's answer to address a FORFILES
design flaw. This technique effectively enhances FORFILES
, so that it identifies files last modified between two dates (or a number of days). The difficulty as I see it is that the FORFILES
"files identified" output is redirected to the CON
device. This means that the output is not available to FOR /F
loops for further processing. So my "quick fix" was to redirect the output to a temporary file, which the FOR /F
loops have access to. I'm wondering if there's some file descriptor magic that could be inserted to avail the output to FOR
.
Here is my (non-destructive) script:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET BACKUPFILEMASK=*.7z
SET DAYS_OLD_EARLIEST=183
SET DAYS_OLD_LATEST=365
SET TMPFILENAME=thin_out_logging.txt
FOR /L %%A IN (%DAYS_OLD_EARLIEST%,7,%DAYS_OLD_LATEST%) DO (
ECHO Iteration: %%A
SET /A ADDWEEK=%%A+7
>NUL 2>&1 FORFILES /M %BACKUPFILEMASK% /D -%%A /C "CMD /C IF @ISDIR==FALSE 2>NUL FORFILES /M @FILE /D -!ADDWEEK! || >> "%TMP%\%TMPFILENAME%" ECHO @FILE"
FOR /F %%B IN ('TYPE "%TMP%\%TMPFILENAME%" ^| FIND "" /V /C') DO SET /A LINES=%%B
ECHO Lines counted for week: !LINES!
IF !LINES! GEQ 2 (
FOR /F "skip=1 usebackq tokens=*" %%C IN ("%TMP%\%TMPFILENAME%") DO ECHO DEL %%C
)
ECHO ---
BREAK>"%TMP%\%TMPFILENAME%"
)
DEL "%TMP%\%TMPFILENAME%"