@echo off setlocal enabledelayedexpansion :: Check if directory path was provided as argument if "%~1"=="" ( echo Usage: delemptydirs.cmd "C:\Path\To\Directory" echo. echo Example: delemptydirs.cmd "C:\Users\YourName\Documents" echo. pause exit /b 1 ) :: Set the target directory set "TARGET_DIR=%~1" :: Verify the directory exists if not exist "%TARGET_DIR%" ( echo Error: Directory "%TARGET_DIR%" does not exist. pause exit /b 1 ) echo Starting cleanup of empty folders in: %TARGET_DIR% echo. :: Counter for deleted folders set /a DELETED_COUNT=0 :: Function to delete empty folders recursively :delete_empty_folders for /f "delims=" %%d in ('dir "%TARGET_DIR%" /ad /b /s 2^>nul') do ( :: Check if directory is empty (no files and no subdirectories) dir "%%d" /a /b 2>nul | findstr "^" >nul if errorlevel 1 ( echo Deleting empty folder: %%d rmdir "%%d" 2>nul if !errorlevel! equ 0 ( set /a DELETED_COUNT+=1 ) else ( echo Warning: Could not delete "%%d" - may be in use or access denied ) ) ) :: Check if any folders were deleted and run again if needed :: (parent folders might become empty after deleting subfolders) if %DELETED_COUNT% gtr 0 ( echo. echo Pass completed. Checking for newly empty parent folders... set /a DELETED_COUNT=0 goto delete_empty_folders ) echo. echo Cleanup completed! echo All empty folders have been removed from: %TARGET_DIR% echo. pause