Batch script to delete all empty subdirectories.

Filed under: Uncategorized — Apneet Jolly at 2:16 pm on Thursday, May 15, 2008

I needed a script to delete all empty subdirectories, but the examples I found failed with directories with spaces in them, or would not let me pass the directory name to the script.

This bat file will do the trick.


@echo off
for /f "delims=" %%i in ('dir "%~f1" /ad /b /s ^| sort /R') do rd "%%i" 1>NUL 2>&1

The batch file will list all directories, in reverse order, and then attempt to delete each one.
rd will only delete empty directories.
The delims parameter stops spaces from being used as a delimiter.
%~f1 lets you pass a directory name to the script.

We use IO redirection at the end of the script to prevent warnings from being displayed on screen.
1>NUL 2>&1
This code says to redirect standard output (handle 1) to NUL, and also take sderr (handle 2) and redirect that to handle 1.

Thanks to Raymond Chen for the original code.

1 Comment »

562

Comment by Anees

November 18, 2008 @ 5:08 am

What if i want to give the path of a folder which exists in different drive , not the drive from which i execute the batch.

for /f “delims=” %%i in (’dir “%D:\test” /ad /b /s ^| sort /R’) do rd “%%i” 1>NUL 2>&1

Here if i execute this from “C: “. it gives me an error.
Could you please help me on this.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>