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
Microsoft DOSMicrosoft Legacy OS

Avatar of undefined
Last Comment
Bill Prew

8/22/2022 - Mon
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
Bill Prew

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
jpertchik

This answer was neat and tidy. Worked the first time. No need to fill in specifics in code snippit. Way cool. Thanks loads!
Bill Prew

Glad that was helpful, thank you.

~bp
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23