Search code examples
filebatch-fileorganization

Batch to delete empty directories (and state which directories aren't empty?)


I'm using:

for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"
pause

which returns:

The directory is not empty.

for any nonempty directories. Is there any way for it to list specifically which directories aren't empty instead of a vague statement? I know it's not much effort to manually check the directories, but this is part of a larger script that I'm trying to make more user-friendly.


Solution

  • rd returns an ERRORLEVEL you can use, just change:

    rd "%%d"
    

    To this:

    rd "%%d" || (echo Not empty: %%d)
    

    To remove error message from rd too just redirect stderr to nul:

    rd "%%d" 2>nul || (echo Not empty: %%d)