Batch Script to Delete files from Folders and Sub Folders Older than 2 months old.
Posted on 2011-05-03
Hi! I was given the script below by billprew. My request was to be able to check folders and delete files older than 2 months.
I now have a question that's related to my intial question. I do need a script that deletes files that are older than 2 months old.
But I would need to script to delete files that are located in subfolders as well. For example, we have D:\Users.
Within the users directories, you would have many sub-folders and sub-sub folders.
I need help with a batch script that checks a specific drive, or folder and its sub folders and deletes files that are older than 1 month, or 2 months.
REM Define base for folders, and days to keep old folders
REM Get todays date (MM/DD/YYYY), convert to julian for age checks
call :jDate jToday %DATE:~-10%
REM Process all Files in the directory, delete if old
for %%A in ("%BaseDir%\*.*") do (
call :jDate jFile %%~tA
set /A FileAge = !jToday! - !jFile!
if !FileAge! GTR %DaysToKeep% (
ECHO File:[%%A] is [!FileAge!] days old and would be deleted
REM del "%%~A"
REM Subroutine to calculate julian date
:jDate return-variable date-string(MM/DD/YYYY)
set /A mm=1%DateStr:~0,2%-100
set /A dd=1%DateStr:~3,2%-100
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
set /a %~1=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4