Remove empty folders and subfolders

This little batch file scans the directory that was provided as a parameter and all its sub-directories for empty folders and deletes them, including the provided folder itself, if it is empty as well (or became empty after all empty sub-folders were removed).

RemoveEmptySubFolders.bat

@echo off
set Folder=”%~1″
if %Folder%==”” @echo Syntax RemoveEmptySubFolders Folder&goto :EOF
if not exist %Folder% @echo Syntax RemoveEmptySubFolders Folder – %Folder% not found.&goto :EOF
setlocal

REM REMOVE EMPTY SUBFOLDERS

for /f “tokens=*” %%A in (‘dir /ad /s /b %Folder% ^|Sort /Reverse’) do (
rmDir “%%A” 2>NUL
)

REM REMOVE FOLDER, IF EMPTY

rmDir %Folder% 2>NUL
endlocal

Posted in Batch files, Microsoft and tagged , .

Leave a Reply