CMD.exe recursion in batch: Deleting empty subdirectories

This article addresses one specific use case for recursion in batch: Recursively looping through a directory (also called a folder) and its sub directories.

Normally, this is a pain, and it took me a while to come up with an algorithm that works.

For recursion to work correctly, you need:

a) Subroutines, and

b) Local variables.

CMD.EXE supports the first one, but local variables are a pain: You can only use SETLOCAL/ENDLOCAL, which prevents any information to be returned to any calling level (except the ERRORLEVEL).

Here is a solution, implemented as a script that recursively deletes empty sub directories of the current directory, and traverses all the way down the directory tree:

That’s it!