# DOS Batch file to delete folders by date range



## gwestergren

I have a folder that i have to clean out weekly but only want to delete a certain range of folders that are older then a week and start with a number. 

I'd like to create a batch file that could do this in dos but am not sure of how to go about this.

Any help would be greatly appreciated.


----------



## TheOutcaste

Welcome to TSG!

What range/format is the number? 
one, two, or more digits?
any leading zeros?
any chance of a negative number?

How do you want to determine date, by date created, date modified, or is the date coded in the folder name?
Do you want to see a list of the folders that will be deleted, with a Y/N prompt, or just delete folders that match the criteria automatically?

Jerry


----------



## gwestergren

The folders have the format of 10 numbers all starting with the number 1. The ones to be deleted are determined by the Date Modified. 

So for example in detail view "1630890112 File folder 11/17/2008 4:49 AM"

Need to be able to delete any folders older then 7 days. A list of folders would be great with a Y/N promt.

I attached a screen shot of what the folder contents look like if that helps.


----------



## TheOutcaste

The following should do what you want.
If you copy and paste from this post you'll have to manually edit the lines just below the lines in red. Those 3 lines contain a TAB character. Copying them changes it to spaces, so I've also attached the script as a text file. Name it what ever you want and save it with a .bat or .cmd extension.
I've tested this under English US and English UK settings and it seems to get the date and time formats correct.
It should only find folders with names that are exactly 10 characters, all numeric, and start with a 1.

All folders older than 7 days will be listed first. You'll have the option to delete all, none, or be prompted for each folder.

You'll need to edit the blue lines below to set the path to the folder that contains the folders and change the # of days if desired


Code:


@Echo Off
Setlocal EnableDelayedExpansion
:: User Variables
:: Set this to the number of days you want to keep
[COLOR=Blue]Set _DaysKept=7[/COLOR]
:: Set this to the folder that contains the folders to check and delete
[COLOR=Blue]Set _Path=C:\Test1[/COLOR]
:: Get todays date
Call :GetDate
Set _yy=%_fDate:~,4%
Set _mm=%_fDate:~4,2%
Set _dd=%_fDate:~6,2%
:: Convert todays date to Julian
Call :JDate %_yy% %_mm% %_dd%
Set _JToday=%_JDate%
:: Set delete date
Set /a _DelDate=_JToday-%_DaysKept%-1
:: Get time format, _iTime will be 0 if 12 hourt clock, 1 if 24 hour clock
[COLOR=Red]:: Delims= is a TAB followed by a space in the next line[/COLOR].
[COLOR=Red]:: If you copy this code, you must edit this line[/COLOR]
For /F "TOKENS=2* DELIMS=     " %%A In ('REG QUERY "HKCU\Control Panel\International" /v iTime') Do Set _iTime=%%B
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PushD %_Path%
Set _s=s
If %_DaysKept%==1 set _s=
Echo Please wait, searching for folders more than %_DaysKept% day%_s% old
If %_iTime%==0 (Set _Tok=1,4*) Else (Set _Tok=1,3*)
For /F "tokens=%_Tok% skip=4" %%I In ('dir "%_Path%\1*" /AD /OD /TW ^|Findstr /E "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"') Do (
Set _Name=%%K
  If "!_Name:~10!"=="" If %%J==^<DIR^> (
    Call :GetDate %%I
    Call :JDate !_fDate:~,4! !_fDate:~4,2! !_fDate:~6,2!
    If !_JDate! LEQ %_DelDate% (
      If Exist "%temp%\tf}1{" (
        Echo %%I:%%~fK >>"%temp%\tf}1{"
        ) Else (
        Echo.>"%temp%\tf}1{"
        Echo Do you wish to delete the following folders?>>"%temp%\tf}1{"
        Echo Date       Name>>"%temp%\tf}1{"
        Echo %%I:%%~fK >>"%temp%\tf}1{"
      )) Else (
      Goto :_allFound
      )))
PopD
:_allFound
If Not Exist "%temp%\tf}1{" Echo No Folders Found to delete&Goto _Done
Type "%temp%\tf}1{" | More
Set _rdflag= /q
:_Prompt1
Set /P _resp=Delete All, None, or Prompt for each (A/N/P)?
If /I "%_resp:~0,1%"=="N" Goto _Done
If /I "%_resp:~0,1%"=="A" Goto _Removeold
If /I NOT "%_resp:~0,1%"=="P" (Echo (A/N/P only please)&Goto _Prompt1
Set _rdflag=
:_Removeold
For /F "tokens=1* skip=3 Delims=:" %%I In ('type "%temp%\tf}1{"') Do (
 If "%_rdflag%"=="" Echo Deleting
 rd /s%_rdflag% "%%J")
:_Done
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
Goto:EOF
::===================================::
::                                         ::
::   -   S u b r o u t i n e s   -   ::
::                                         ::
::===================================::
:JDate
:: Convert date to Julian
:: Arguments : YYYY MM DD
:: Returns   : Julian date in variable _JDate
:: Usage
::Call :JDate %__GYear% %_GMonth% %_GDay%
:: First strip leading zeroes; a logical error in this
:: routine was corrected with help from Alexander Shapiro
::Code taken from datediff.bat written by Rob van der Woude
::http://www.robvanderwoude.com
Set _JMM=%2
Set _JDD=%3
IF 1%_JMM% LSS 110 Set _JMM=%_JMM:~1%
IF 1%_JDD% LSS 110 Set _JDD=%_JDD:~1%
::
:: Algorithm based on Fliegel-Van Flandern
:: algorithm from the Astronomical Almanac,
:: provided by Doctor Fenton on the Math Forum
:: (http://mathforum.org/library/drmath/view/51907.html),
:: and converted to batch code by Ron Bakowski.
Set /A _JMonth1 = ( %_JMM% - 14 ) / 12
Set /A _JYear1  = %1 + 4800
Set /A _JDate  = 1461 * ( %_JYear1% + %_JMonth1% ) / 4 + 367 * ( %_JMM% - 2 -12 * %_JMonth1% ) / 12 - ( 3 * ( ( %_JYear1% + %_JMonth1% + 100 ) / 

100 ) ) / 4 + %_JDD% - 32075
For %%A In (_JMonth1 _JYear1) Do Set %%A=
Goto:EOF
:GetDate
:: This subroutine will always display the same results,
:: for the date independent of "International" settings.
:: This batch file uses REG.EXE from the NT Resource Kit
:: (already installed with WinXP and Vista)
:: to read the "International" settings from the registry.
:: Date is returned as yyyymmdd in variable _fdate
:: Modified from SortDate Written by Rob van der Woude
:: http://www.robvanderwoude.com
::
If NOT [%1]==[] Set Date=%1
If "%date%A" LSS "A" (Set _NumTok=1-3) Else (Set _NumTok=2-4)
[COLOR=Red]:: Delims= is a TAB followed by a space in the next two lines[/COLOR].
[COLOR=Red]:: If you copy this code, you must edit these two lines[/COLOR]
For /F "SKIP=3 TOKENS=2* DELIMS=     " %%A In ('REG QUERY "HKCU\Control Panel\International" /v iDate') Do Set _iDate=%%B
For /F "SKIP=3 TOKENS=2* DELIMS=     " %%A In ('REG QUERY "HKCU\Control Panel\International" /v sDate') Do Set _sDate=%%B
IF %_iDate%==0 For /F "TOKENS=%_NumTok% DELIMS=%_sDate% " %%B In ("%date%") Do Set _fdate=%%D%%B%%C
IF %_iDate%==1 For /F "TOKENS=%_NumTok% DELIMS=%_sDate% " %%B In ("%date%") Do Set _fdate=%%D%%C%%B
IF %_iDate%==2 For /F "TOKENS=%_NumTok% DELIMS=%_sDate% " %%B In ("%date%") Do Set _fdate=%%B%%C%%D
Goto:EOF

HTH

Jerry


----------



## gwestergren

Thanks Jerry,

I'll test it out and let you know what happens 

Appreciate the help!!!

Greg


----------



## TheOutcaste

Seems like the forum editor has modified the attached text file and has converted the TAB characters to spaces, and word wrapped a long line. The sample in the code block was also split before I added the code tags (3 lines up from :GetDate subroutine).
I've corrected that, and modified the file slightly so a variable is used for the tab-space combination so there is only one line that potentially needs to be edited.
And I've attached it as a zip file and used a .cmd extension so hopefully it won't get modified in the future.

If anyone has downloaded the test.txt file and it didn't work, try the attached zip file instead.

Jerry


----------



## dcookie

Just take a look at code posted by Outcaste! 

One command does it in *nix.

find dir -atime +7 -exec rm {} \;

Get Cygwin and set yourself free!

---dale


----------



## bsaumier

Hey there i have almost the same issue but i want to delete folders based on: it will keep the last 6 folders created in each subfolder so i need a batch file that will check the current time the go through the folder and check each subfolders time and only keep the last 6 folders and delete the other folders and their content is there any way to do this?


----------



## TheOutcaste

Welcome to TSG!

It's usually best to start your own thread, especially if it's "almost the same issue". You can always include a link referring to the other thread. Not that critical with stuff like this, but still a good habit to develop.

This is actually easier. If you just want to keep the *N* most recent folders, you don't need to check the date. Just skip the *N* newest folders, doesn't matter what the actual date is. If there are fewer than *N* folders, none will be deleted.



Code:


@Echo Off
:: User Variables
:: Set this to the number of folders you want to keep
Set _NumtoKeep=[B][COLOR=Red]6[/COLOR][/B]
:: Set this to the folder that contains the folders to check and delete
Set _Path=C:\Test
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PushD %_Path%
Set _s=%_NumtoKeep%
If %_NumtoKeep%==1 set _s=single
Echo Please wait, searching for folders other than the %_s% most recent
For /F "tokens=* skip=%_NumtoKeep%" %%I In ('dir "%_Path%" /AD /B /O-D /TW') Do (
  If Exist "%temp%\tf}1{" (
    Echo %%I:%%~fI >>"%temp%\tf}1{"
    ) Else (
    Echo.>"%temp%\tf}1{"
    Echo Do you wish to delete the following folders?>>"%temp%\tf}1{"
    Echo Date       Name>>"%temp%\tf}1{"
    Echo %%I:%%~fI >>"%temp%\tf}1{"
  ))
PopD
If Not Exist "%temp%\tf}1{" Echo No Folders Found to delete & Goto _Done
Type "%temp%\tf}1{" | More
Set _rdflag= /q
:_Prompt1
Set /P _resp=Delete All, None, or Prompt for each (A/N/P)?
If /I "%_resp:~0,1%"=="N" Goto _Done
If /I "%_resp:~0,1%"=="A" Goto _Removeold
If /I NOT "%_resp:~0,1%"=="P" (Echo (A/N/P only please)&Goto _Prompt1
Set _rdflag=
:_Removeold
For /F "tokens=1* skip=3 Delims=:" %%I In ('type "%temp%\tf}1{"') Do (
 If "%_rdflag%"=="" Echo Deleting
 rd /s%_rdflag% "%%J")
:_Done
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"

HTH

Jerry


----------

