Link to home
Start Free TrialLog in
Avatar of jpertchik
jpertchikFlag for United States of America

asked on

deleting files in windows that are older than 2 days using bat file

I need to schedule the deletion of .bak files using whatever tools weather it be cmd.exe or power shell based upon number of days old:

C:\Backup>>>>>>>>>>>Delete the contents of this folder after 2 days.

I plan to execute the .bat file using the windows scheduler or if there is a neater way to do it, by all means please elaborate.

As usual thanks in advance!
JPertchik
Avatar of Bill Prew
Bill Prew

Here is a pure BAT solution.  It can also be done easily (less code) in VBS, or you could use the DELAGE32 utility from this location:

http://www.horstmuc.de/win/delage.htm
http://www.horstmuc.de/wbat32.htm

@echo off
setlocal EnableDelayedExpansion

REM Define base for folders, and days to keep old folders
Set BaseDir=c:\backup
set DaysToKeep=2

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% (
    del "%%~A"
  )
)

REM Done
exit /b

REM Subroutine to calculate julian date
:jDate return-variable date-string(MM/DD/YYYY) 
  set DateStr=%~2
  set yy=%DateStr:~6,4%
  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
  exit /b

Open in new window

~bp
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jpertchik

ASKER

This answer was neat and tidy. Worked the first time. No need to fill in specifics in code snippit. Way cool. Thanks loads!
Glad that was helpful, thank you.

~bp