Oops, sorry 'bout that.
%nullDir% is a fancy 'macro', a small batch routine contained inside a variable so you don't have to issue a CALL command... which happens to be just about the slowest thing in batch. A more complete and useful version looks like this:
Code: Select all
@ECHO OFF
:: define a newline with line continuation
(SET \n=^^^
%= This defines an escaped Line Feed - DO NOT ALTER =%
)
:: recursively remove all empty folders from a directory tree
SET nullDir=FOR %%# IN (1 2)DO IF %%#==2 (%\n%
FOR /F "tokens=*" %%: IN ('DIR /AD-S/B/S !##! 2^^^>NUL ^^^|SORT/R')DO RD "%%:"^>NUL 2^>^&1%\n%
ENDLOCAL%\n%
)ELSE SETLOCAL EnableDelayedExpansion^&SET ##=%= \Path\to\Folder =%
:: call the macro
%nullDir% %1
EXIT /B 0
SETLOCAL is issued inside the routine so the macro can be used in batch scripts that
don't use DelayedExpansion. SETLOCAL is used after the ELSE statement to assure that it's the first statement executed by the routine and avoid accidentally clobbering any variables in the script that calls it (maybe it's using %##%? you never know...). Remember, SETLOCAL/ENDLOCAL is a way to keep local variables local, as opposed to global. This is all needlessly fancy, of course.
Code: Select all
@ECHO OFF
:nullDir folderName
FOR /F "tokens=*" %%: IN ('DIR /AD-S/B/S %1 2^>NUL ^| SORT/R') DO RD "%%:" >NUL 2>&1
EXIT /B 0
...is all you need, just make sure your parent folder is used for %1. It works by issuing a DIR /A(ttribute)D(irectories)-(ignore)S(ystem folders)/B(are info)/S(earch recursive) and piping it into SORT.EXE /R(everse). This assures that the 'bottom-most' folders are removed first so that nested folders are properly emptied, and conveniently
RD will remove only empty folders unless the /S switch is used. Of course, any commands you wish may be used. To list the folders as they are emptied, perhaps try:
Code: Select all
@ECHO OFF
:nullDir folderName
FOR /F "tokens=*" %%: IN ('DIR /AD-S/B/S %1 2^>NUL ^| SORT/R') DO (
RD "%%:" >NUL 2>&1
IF NOT EXIST "%%:" ECHO %%:
)
EXIT /B 0