JSI Tip 7740. How can I delete those files in a folder that were last written within a given date range?

Jerold Schulman

February 10, 2004

1 Min Read
ITPro Today logo in a gray background | ITPro Today


I have scripted Purge.bat to delete files in a specified folder whose last written date falls within a given date range.

The syntax for using Purge.bat is:

purge Folder From_YYYYMMDD To_YYYYMMDD [/S]

Where:

Folder        is the path to the folder you want to purge.From_YYYYMMDD is the lower date in the range, using YYYYMMDD format.To_YYYYMMDD   is the upper date in the range, using YYYYMMDD format./S            is an optional parameter that also purges matching files in all sub-folders.

Purge.bat contains:

@echo offsetlocalif {%3}

{} goto Syntaxset folder=%1#set folder=%folder:"=%set folder=%folder:#=%set folder=%folder:#=%if not exist "%folder%*.*" goto Syntaxset fromdt=%2set todt=%3if "%fromdt%" GTR "%todt%" goto Syntaxif "%fromdt:~7,1%" EQU "" goto Syntaxif "%todt:~7,1%" EQU "" goto Syntaxif "%fromdt:~8,1%" NEQ "" goto Syntaxif "%todt:~8,1%" NEQ "" goto Syntaxset xx=if {%4}

{} goto beginset xx= %4set xx=%xx:"=%if /i "%xx%" NEQ " /s" goto Syntax:beginpushd "%folder%"for /f  "Tokens=*" %%s in ('dir "%folder%*.*" /as /ah /a-d /b%xx%') do ( set file=%%s call :parse)popdendlocalexit /b 0:Syntax@echo Syntax: purge Folder From_YYYYMMDD To_YYYYMMDD [/S]endlocalexit /b 1:parseset file=%file:)=^)%set file=%file:(=^(%for /f  "Tokens=1-3 Delims=/ " %%a in ('dir "%file%" /as /ah /a-d /TW ^|Findstr /C:"/"') do ( set /a month=100%%a%%100 set /a day=100%%b%%100 set /a year=10000%%c%%10000)If %year% GTR 99 goto compdtif %year% GTR 80 set year=19%year%&goto compdtif %year% LSS 10 set year=0%year%set year=20%year%:compdtif %month% LSS 10 set month=0%month%if %day% LSS 10 set day=0%day%set filedt=%year%%month%%day%if "%filedt%" LSS "%fromdt%" goto :EOFif "%filedt%" GTR "%todt%" goto :EOFdel /q "%file%"



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like