# Batch script to delete the oldest folders in a directory



## loss4words (Apr 4, 2007)

Hi guys,

So I have the following script which copies the contents of user's "My Documents" folder to a specified location on a hard drive with a time stamp, and then deletes and recreates the user's "My Documents" folder. I wanted to use this as a startup or a shutdown script and so far it seems to be working.

My question is, is there anything I could add to the script to delete the oldest folders that will created in "C:\backup" directory, for example anything older than 10 days, or how would you write a separate batch file that would do something like this?



> set SourceDir=C:\Documents and Settings\username\My Documents
> set TargetDir=C:\backup\%date:~-4,4%-%date:~-10,2%-%date:~-7,2% %time:~0,2%h%time:~3,2%m%time:~6,2%s
> xcopy /i /s /e "%sourcedir%" "%TargetDir%"
> rd /s /q "%SourceDir%"
> mkdir "C:\Documents and Settings\username\\My Documents"


Sorry for being such a newbie. Thanks


----------



## TheOutcaste (Aug 8, 2007)

This will do it. Set _Prompt to false in line 8 to automatically delete instead of prompting.
If run today (Jan 25, 2011) and set to keep 10 days it will keep folders whose name starts with 20110115 (Jan 15, 2011) and later.
It checks that the first 8 characters of the name are numbers, and checks that the month number is less than 20, and the date less than 40.

```
@Echo Off
:: Delete folders by date contained in folder name
:: Written by TheOutcaste for http://forums.techguy.org
SetLocal EnableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: User Variables
:: Set this next line to False to automatically delete all folders found
Set _Prompt=True
:: Set this to the number of days you want to keep
Set _DaysKept=10
:: Set this to the folder that contains the folders to check and delete
Set _Path=C:\Backup
:::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Get todays date
Call :_GetDate
:: Convert todays date to Julian
Call :JDate %_fDate%
Set _JToday=%_JDate%
:: Set delete date
Set /a _DelDate=_JToday-%_DaysKept%-1
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PushD %_Path%
Set _s=s
If %_DaysKept%==1 Set _s=
If /I %_Prompt%==True Echo Please wait, searching for folders more than %_DaysKept% day%_s% old
For /F "Tokens=1 Delims=" %%I In ('Dir "%_Path%" /AD /B /ON^|Findstr /B /R "[0-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9]"') Do (
  Call :JDate %%I
  If !_JDate! LEQ %_DelDate% (
    If Exist "%temp%\tf}1{" (
      Echo %%I>>"%temp%\tf}1{"
    ) Else (
      (Echo.
      Echo Do you wish to delete the following folders?
      Echo      Name
      Echo %%I
      )>"%temp%\tf}1{"
    )
  ) Else (
    Goto :_allFound
  )
)
:_allFound
If Not Exist "%temp%\tf}1{" Echo No Folders Found to delete&Goto _Done
Set _rdflag= /q
If /I %_Prompt%==False Goto _Removeold
Type "%temp%\tf}1{" | More
:_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 "skip=3 Delims=" %%I In ('Type "%temp%\tf}1{"') Do (
 If "%_rdflag%"=="" Echo Deleting
 rd /s%_rdflag% "%%I")
:_Done
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PopD
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
:: Modified to handle months and days witout leading zeros
:: By TheOutcaste http://forums.techguy.org
Set _JYY=%1
Set _JMM=%_JYY:~4,2%
Set _JDD=%_JYY:~6,2%
Set _JYY=%_JYY:~0,4%
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  = %_JYY% + 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 batch file will always display the same results,
:: 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 by TheOutcaste http://forums.techguy.org from
:: SortDate Written byRob van der Woude http://www.robvanderwoude.com
:: to check for two digit years
::
Set _Date=%Date%
If "%_Date%A" LSS "A" (Set _NumTok=1-3) Else (Set _NumTok=2-4)
Set _TDYM=
:: Default Delimiter of TAB and Space are used
For /F "Tokens=2*" %%A In ('Reg Query "HKCU\Control Panel\International" /v iDate') Do Set _iDate=%%B
For /F "Tokens=2*" %%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
If "%_fdate:~7,1%"=="" For /F "Tokens=3 skip=3" %%I In ('Reg Query "HKCU\Control Panel\International\Calendars\TwoDigitYearMax" /V 1 2^>Nul') Do Set _TDYM=%%I
If Defined _TDYM (Set _MaxY=%_TDYM:~2%&Set _Cent=%_TDYM:~0,2%) Else (Set _MaxY=29&Set _Cent=20)
Set /A _Cm1=_Cent-1
If "%_fdate:~7,1%"=="" If %_fdate:~0,2% LEQ %_MaxY% (Set _fdate=%_Cent%%_fdate%) Else (Set _fdate=%_Cm1%%_fdate%)
```


----------

