Batch file to del folders older than N days

October 20, 2010 at 15:01:39
Specs: Windows Server 2003
Hello. I need a batch file to delete folders and the content inside older than N days...


name of folder = "test+date"

\test20101020 (2010 = year; 10 = month; 20 = day)
\test20101015 (2010 = year; 10 = month; 15 = day)
\test20101014 (2010 = year; 10 = month; 14 = day)

So, what i need to do is to get the newest date from the folder name and delete all folders 7 days older.

NOTE: i need to delete all the folders and the content inside it

If anyone has any ideia on how to make the batch file to do that let me know.

Thanks a lot.

See More: Batch file to del folders older than N days

Report •

October 22, 2010 at 02:07:39
When posting for assist with dates please always show your Date format.

Test this, change the Path\to\folders\ to your actual path. When you are satisfied it will do what you want remove the REM to delete folders.

Good luck.

@echo off
setlocal enabledelayedexpansion

:: Syntax = Batfilename n (where n is the number of days)

if [%1] equ [] echo Number of days not entered - job terminated&exit /b

:: Get today's date less %1 days.

set vbs=%temp%\vbs.vbs

> %vbs% echo WScript.Echo DateAdd("d",-%1,Date)

for /f "tokens=*" %%a in ('cscript //nologo %vbs%') do set newdate=%%a

del %vbs%

:: Find/set date format.

if "%date%A" lss "A" (set toks=1-3) else (set toks=2-4)

for /f "tokens=%toks% delims=./: " %%1 in ("!newdate!") do (
    set one=%%1&set two=%%2&set tre=%%3

for /f "tokens=5-7 delims=:()- " %%1 in ('echo.^|date') do (
    set first=%%1&set secnd=%%2&set third=%%3
set !first!=!one!&set !secnd!=!two!&set !third!=!tre!
set newdate=!yy!!mm!!dd!

:: Compare today's date -%1 with folder date.

Pushd Path\to\folders||echo Pushd failed - job terminated&&exit /b

echo Folders to be deleted.

for /f "tokens=*" %%1 in ('dir /b /ad test*') do (
    set foldernamedate=%%1
    set foldernamedate=!foldernamedate:~4!
        if !foldernamedate! lss !newdate! (
           echo %%1
REM           echo y|del %%1\*.*>nul&rd %%1


Report •
Related Solutions

Ask Question