Script looks like:
Code: Select all
@ECHO OFF
SET KEEP_DAYS=7
SET KEEP_2WEEKS=14
SET KEEP_1YEAR=365
SET ROOT_DIR=C:\Users\test\Desktop\tickets\BAT_TEST\test_directory
SET EXCLUDE_DIR=archive
SET DIR_2WEEKS=\archive\keep-two-weeks
SET DIR_1YEAR=\archive\keep-one-year
SET LOG_FILE=C:\Users\test\Desktop\tickets\BAT_TEST\cleanup.log
IF NOT "%1"=="-D" (
ECHO Specify -D parameter to confirm deletion start
GOTO :EOF
)
IF %KEEP_DAYS% LSS 7 (
ECHO KEEP_DAYS value %KEEP_DAYS% is too small!
GOTO :EOF
)
ECHO Deleting files older than %KEEP_DAYS% day(s). >> %LOG_FILE%
ECHO Start %date:~-11% %time% >> %CD%\%date:~-11%log >> %LOG_FILE%
SET /A COUNT=1
for /D %%E in (%ROOT_DIR%\*) do (
ECHO Processing %%E >> %LOG_FILE%
for /D %%D in (%%E\*) do ECHO %%D | findstr /v /c:"%EXCLUDE_DIR%" >> %LOG_FILE% && call :deleteFiles %%D
ECHO Deleting files in archive folders. >> %LOG_FILE%
if exist %%E%DIR_2WEEKS% call :deleteArchive %%E%DIR_2WEEKS% %KEEP_2WEEKS%
if exist %%E%DIR_1YEAR% call :deleteArchive %%E%DIR_1YEAR% %KEEP_1YEAR%
ECHO Finished %%E >> %LOG_FILE%
)
GOTO :DONE
:deleteFiles
FORFILES /p %1 /S /M * /C "CMD /C if @isdir==FALSE del /F /Q @PATH && echo @PATH @FSIZE @FDATE" /D -%KEEP_DAYS% >> %LOG_FILE%
GOTO :EOF
:deleteArchive
FORFILES /p %1 /S /M * /C "CMD /C del /F /Q @PATH && echo @PATH @FSIZE @FDATE" /D -%2 >> %LOG_FILE%
GOTO :EOF
:DONE
::ECHO Total files deleted %COUNT% >> %LOG_FILE%
ECHO Stop %date:~-11% %time% >> %LOG_FILE%