Command line Batch File to Remove Direcories, using a Wild Card!

We have a bunch of web services which log details of requests that come in, in folders named using the current date- in the format YYYY-MM-DDD-HH-MM-SS. I wanted to produce a simple cleanup batch file which we could run every month to bin all logs for transactions which happened 3 months ago- using the dos commands which exist on Windows Server 2003.

The dos “del” command allows you to delete using wild cards – so for example “dev 2009-07-*” would erase any files starting with “2009-07-”; However this doesn’t work with folders- so it fell to the rd (remove directory) command- but this doesn’t support wild cards (I’m assuming for safety- to stop you permanently erasing 100′s of folders and their contents accidently- remember there’s no recycle bin when you delete from the command line!).

To get around this I created a simple Batch file which accepted a wildcard as a parameter, then removes all those folders at the current level (it wont check recursivly). Just in case this is of use to anyone else, here’s the code;

REM - performs a remove directory, with wildcard matching - example ; rd-wildcard 2007-*
dir %1 /b >loglist.txt
setlocal enabledelayedexpansion
for /f %%a in (./loglist.txt) do ( 
	rd /s /q %%a
del /q loglist.txt
  1. #1 by SenHu on November 19, 2009 - 16:55

    Nice work. You found out a need and created a script for it – so others can use it. Thank you.

    Have you posted any scripts in biterscripting of late ? I find it is very useful in circumventing DOS batch scripts’ shortcomings.


  2. #2 by shawson on November 26, 2009 - 18:00

    Thanks for your comment, glad you found it useful. Nope, never seen the biterscripting site? I shall have to have a butchers!

  3. #3 by Tellef on July 1, 2010 - 11:18

    Hi, thank you for a nice and simple script!

    It might be worth mentioning though, that if you run this script and forget to give a parameter, it will delete absolutely every subfolder in your tree…

  4. #4 by shawson on July 13, 2010 - 11:06

    haha yes! good point, well worth raising!

  5. #5 by Justice Cairns on August 4, 2012 - 09:47

    Aw, this was a really nice post. In concept I want to put in writing like this moreover – taking time and precise effort to make an excellent article… but what can I say… I procrastinate alot and on no account seem to get one thing done.

(will not be published)