Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
hello,
I have a folder that I want to periodiclly clean out old folders. for example a folder is created every day that looks like 20080304. I want to Keep the last 30 folders and delete any folder dated before that. I am just getting started using the SET and FOR commands and need a little help getting this one going.
Thank in advance,

Try This .. It Will Skip The Latest 30 Folders And Delete The Rest .. It Is In Debug Mode ... Remove The Echo from line 5 after "do" to actually make it delete the folders
:: --- BATCH SCRIPT START ---
@echo off
setlocal
set source=C:\source
pushd "%source%"
for /f "skip=30 delims=" %%a in ('dir /b /a:d /o:-d 2^>NUL') do echo rmdir /s /q "%%a"
popd
endlocal
:: --- BATCH SCRIPT END ---

#1, no need to popd or end; it pops & ends local when the bat quits.
=====================================
If at first you don't succeed, you're about average.M2

thanks for all the responses,
unfoutunately there are other folders contained in the directory. When i run this script it deletes folders by creation date. Is there a way to specify it to read folder names instead of creation date. the folders are in sequential order 20080102,20080103 etc.

FOR /F "skip=30 delims=" %%a IN ('DIR /B /AD 20?????? | SORT /R') DO RD /S /Q "%%a"EDIT: Thanks, devil_himself, I really should learn to not do these past my bed time.

Razor that line looks almost works, for some reason I can use the line 'DIR /B /AD 20?????? | SORT /R'on its own and it does what it is supposed to do. Inside the for command it gives the "| was unexpected at this time." error msg

FOR /F "skip=30 delims=" %%a IN ('DIR /B /AD 20?????? ^| SORT /R') DO RD /S /Q "%%a"
Escape Characters, Delimiters and Quotes
http://www.ss64.com/ntsyntax/esc.html

#7 is correct about escaping the pipe.
But you don't need SORT.
FOR /F "tokens=* skip=30 delims=" %%a IN ('DIR /B/AD/o-n 20??????') DO RD /S /Q "%%a"
)
=====================================
If at first you don't succeed, you're about average.M2

use 'dir /b/ad/TC/o-d' for folders by creation time. User rmdir /q /s to remove folders or directories.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |