delemptydirs.cmd 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. :: Check if directory path was provided as argument
  4. if "%~1"=="" (
  5. echo Usage: delemptydirs.cmd "C:\Path\To\Directory"
  6. echo.
  7. echo Example: delemptydirs.cmd "C:\Users\YourName\Documents"
  8. echo.
  9. pause
  10. exit /b 1
  11. )
  12. :: Set the target directory
  13. set "TARGET_DIR=%~1"
  14. :: Verify the directory exists
  15. if not exist "%TARGET_DIR%" (
  16. echo Error: Directory "%TARGET_DIR%" does not exist.
  17. pause
  18. exit /b 1
  19. )
  20. echo Starting cleanup of empty folders in: %TARGET_DIR%
  21. echo.
  22. :: Counter for deleted folders
  23. set /a DELETED_COUNT=0
  24. :: Function to delete empty folders recursively
  25. :delete_empty_folders
  26. for /f "delims=" %%d in ('dir "%TARGET_DIR%" /ad /b /s 2^>nul') do (
  27. :: Check if directory is empty (no files and no subdirectories)
  28. dir "%%d" /a /b 2>nul | findstr "^" >nul
  29. if errorlevel 1 (
  30. echo Deleting empty folder: %%d
  31. rmdir "%%d" 2>nul
  32. if !errorlevel! equ 0 (
  33. set /a DELETED_COUNT+=1
  34. ) else (
  35. echo Warning: Could not delete "%%d" - may be in use or access denied
  36. )
  37. )
  38. )
  39. :: Check if any folders were deleted and run again if needed
  40. :: (parent folders might become empty after deleting subfolders)
  41. if %DELETED_COUNT% gtr 0 (
  42. echo.
  43. echo Pass completed. Checking for newly empty parent folders...
  44. set /a DELETED_COUNT=0
  45. goto delete_empty_folders
  46. )
  47. echo.
  48. echo Cleanup completed!
  49. echo All empty folders have been removed from: %TARGET_DIR%
  50. echo.
  51. pause