Batch script to test if folder / directory is empty

Yesterday I needed a Dos batch script to check if folder is empty. A little Google search revealed some methods:

  • Using dir and find commands, does not work on non-english Windows versions: www.computing.net
  • Using dir command with /a-d, does not work for folders: www.computing.net
  • Using dir and findstr commands, does not work on non-english Windows versions: windowsitpro.com

If you want something done right do it yourself. Here is a my script:
@echo off

for /F %%i in ('dir /b "c:\test directory\*.*"') do (
   echo Folder is NON empty
   goto :EOF
)

echo Folder is empty or does not exist

Update Sep 21, 2011 – added “or does not exist”. Thanks to the Thump.
Update Jul 5, 2013 – for more code examples see the comments!

This entry was posted in OS, Programming and tagged , , , , , . Bookmark the permalink.

16 Responses to Batch script to test if folder / directory is empty

  1. Dmitry says:

    Brilliant hint. Thank you!

  2. greyfox says:

    I know this is an old post but is there a way to modify this to check inside subfolders?

    I want to see if there is an empty folder (2) inside an empty folder (1) – the empty folder (2) being the only object inside folder (1) – so that I can delete useless folders that will return Not Empty using that script.

    thanks

  3. WishMesh says:

    greyfox,

    You can add /A-D and /S to dir command, to include subfolders, and do not include folders in result.

    dir /b /A-D /S “c:\test directory\*.*”

    I didn’t test it, but it should work fine.

  4. Thump says:

    Hi Maris!

    This is not the best choice.
    If the folder doesn’t exists your code will be executed as like the folder would be empty.

  5. andy_t says:

    This will certainly fail if you got files in some folder that do NOT have an extension (“dmp”) or just an extension but no name (“.svn”).

    This here works on all files, no matter how the name of the file looks like:
    for /F %%N in ('dir /S/B "c:\test directory\*" ^| find /V /C "::"') do (if %%N EQU 0 rd c:\test directory)

  6. Maris says:

    andy_t,

    Thank you for more elegant code!

    However, I just tested and ‘dir *.*’ returns files without extension and files without file name, like ‘dmp.’ and ‘.svn’. Essentially, *.* and * are equal IMO (at least for dos/cmd commands, they however are not equal for all programs, for example 7-zip, see http://www.7-zip.org/faq.html about ‘*.* wildcard’).

  7. andy_t says:

    Yes Maris, you are right there. I was very certain that at least files without extension would fail but interestingly it is listed:

    C:\Temp>dir *.* /b
    .test
    test

  8. tifosi says:

    Hello I want to do this

    1) Delete all the folders and subfolders if they are EMPTY. Re-cursive
    2) Move/Copy the folders Contents to another destination if they have any. This should be re-cursive

    Can the above script works>

    Tifosi

  9. Deadmeat says:

    @REM ------- BEGIN testEmptyFolder.cmd ----------------
    @echo off
    setlocal DisableDelayedExpansion
     
    for /f "tokens=*" %%i in ('dir /b /ad') do (
        set "folder=%%i"
        call :testEmpty
    )
    echo.
    pause
    exit /b
     
    :testEmpty
    for /f "tokens=*" %%j in ('dir /b "%folder:&=^&%\*.*"') do exit /b
    echo %folder:&=^&% is empty or does not exist
    exit /b
     
    :eof
    REM ------- END testEmptyFolder.cmd ------------------

  10. Rose says:

    I love the script deadmeat provided above to output the empty folders. I would like to output a list of folders, to a file, that exclude the empty folders. I’m afraid I do not have a full understanding of batch variables to make the adjustments myself. Can you provide the modifications to do this?

  11. Pieter says:

    On W7 I am trying to use your code to transfer some files when the target directory is empty, as follow:

    set SourceDir=D:\AddToCalibreold
    set TargetDir=D:\AddToCalibre

    for /F %%N in (‘dir /S/B “d:\AddToCalibre\*” ^| find /V /C “::”‘) do (if %%N EQU 0
    set MaxFiles=100
    for /f “tokens=1* delims=[]” %%G in (‘dir /A-D /B “%SourceDir%\*.*” ^|
    find /v /n “”‘) do (
    move “%SourceDir%\%%~nxH” “%TargetDir%\”
    if %%G==%MaxFiles% exit /b 0)
    )

    and the error simply states:

    The syntax of the command is incorrect.
    D:\>for /F %N in (‘dir /S/B “d:\AddToCalibre\*” ^| find /V /C “::”‘) do (if %N EQU 0

    I think it is to do with nested loops, but cannot find something definitive to resolve this. Must I rather call a second script instead of trying to run the code to move the files?

  12. Anonymous says:

    Hi
    here is a snippet that to me somehow is easier and more elegant.
    Teeme contains a string for logging.
    Took me a while to come up with.

    for /f "delims=" %%i in ('dir %am_DirectoryWhereToDeleteEmptyDirs% /s/b/ad ^| sort /r') do (
    :: Untersuche jetzt %%i ob leer und löschbar %TEEME%
        dir /B /A:-D %%i >nul 2>&1 || (
            echo %%i contains no files %TEEME%
                dir %%i /s /b /ad |find /v "" /C >nul 2>&1|| (
                    echo Folder %%i contains no Subfolders either and will be deleted now ^.^.^. %TEEME%
                    rd "%%i" >>%LOG% 2>>&1
                    if {%TRACE%}=={echo} echo. %TEEME%
                )
            )
    )

  13. Andi says:

    Hi,
    Check this out. To me it’s more elegant because it does not contain quite so complicated commands. It took me a while to come up with that.
    REM ///////////////////////////////////////////////////////
    REM ////////////// ITERATE DIRECTORY FOR EMPTY ////////
    REM ////////////// EMPTY SUBDIRECTORIES ////////
    REM ////////////// AND DELETE THEM ///////////
    REM ///////////////////////////////////////////////////////
        
    REM Batch procedure that checks a directory structure for empty folders ^(no files, no subdirs^)
    REM And then works on the empty ones, in this case deletes them
    REM Working on the empty ones proved to be more difficult than working on the ones with data.
    REM
    REM Explanations
    REM am_DirectoryWhereToDeleteEmptyDirs will be iterated including all its Subdirectories
    REM The first dir command within the for checks whether ^%^%i contains files
    REM If it doesn't then the second dir command checks whether ^%^%i contains subfolders
    REM Even though, a simple rd command would not delete a directory with subfolders,
    REM So this really is a matter of elegance.
    REM A command after a double pipe will only be executed if the preceding command is considered to have failed
    REM The parameters ^/s ^/b ^/ad only show a directory that has been found, and it is depicted by its full name only.
    REM The good news here is that the dot and double dot for current and parent directory will be skipped.
    REM Find is now told to search for anything it is being passed, but an empty string.
    REM Since I don't need any output I first limit it to a numeral and then I dump it into nirvana.
    REM The good thing is if nothing has been found then the command is regarded as having failed.
    REM So now I know if it has failed the directory currently being worked on is empty.
    REM And then I happily delete it.
    REM TEEME and Log are special Variables for logging. You don't have to use them.
    REM I have looked around and all I googled was unsatisfactory.
    REM Either too complicated or too much programming or what have you.
    REM Other advantages of this solution is that is spares you of catching errorlevels and of gotos
    REM So I share this with the www community.
    REM Cheers, Andi.
        
    for /f "delims=" %%i in ('dir %am_DirectoryWhereToDeleteEmptyDirs% /s/b/ad ^| sort /r') do (
    :: Testing whether %%i is empty and can be deleted %TEEME%
        dir /B /A:-D %%i >nul 2>&1 || (
            echo %%i contains no files %TEEME%
            dir %%i /s /b /ad |find /v "" /C >nul 2>&1|| (
                echo Folder %%i contains no Subfolders either and will be deleted now ^.^.^. %TEEME%
                    rd "%%i" >>%LOG% 2>>&1
                    if {%TRACE%}=={echo} echo. %TEEME%
                )
            )
    )

  14. Maris, I’ve tried 3 times to post this. ;-) Since this post was one of the most helpful as I was trying to do this as well, I thought it only fair that I post the code I finally got to work. Maris, thanks for posting your original thread! Hope this helps!

    Trying now with no “code” or “quote” tags:

    @echo off
    REM
    REM 7/5/2013
    REM
    REM This script will walk through every directory starting
    REM from where it's run and check them all for the absence
    REM of files AND folders. If it finds a directory with no
    REM files, it will send "File not found" to the screen of the
    REM command prompt and continue checking. If it then finds
    REM that the directory has no subdirectories, it will send
    REM the full path to the "list_of_empty_directories.txt" file
    REM (created in the directory where the script was started).
    REM
    REM Errors: It will, when it gets to the end, call the
    REM "testDIR" function a second time, returning the final empty
    REM directory into to the "list_of_empty_directories.txt" file
    REM twice. I decided I didn't care; if anyone
    REM can fix it, I'd love to see the fix.
    REM

    setlocal DisableDelayedExpansion
    FOR /D /r %%G in ("*") DO (
    set "folder=%%G"
    call :testFILE
    )


    :testFILE
    for /F %%i in ('dir /b /A-D "%folder%\*"') do exit /b
    REM if you’re here, directory has no files
    call :testDIR
    exit /b

    :testDIR
    for /F %%i in ('dir /b /A:D "%folder%\*"') do exit /b
    REM if you’re here, directory has no directories
    echo "%folder%" is totally empty>>list_of_empty_directories.txt
    echo Found an Empty
    exit /b

  15. Maris says:

    Big Ugly Man Doll,

    Fixed code tag for you :)

    Maris

  16. batch-newbie says:

    Thanks for the post and code …

    I wanted to integrate this code into another code and if i just execute “Big Ugly Man Doll” code, it’ll print the last missing directory twice. hence i add goto :end and :end to properly exit ..


    echo ####checking for empty folders ##### >> list_of_empty_directories.txt

    setlocal DisableDelayedExpansion
    FOR /D /r %%G in ("*") DO (
    set "folder=%%G"
    call :testFILE
    )
    goto end

    :testFILE
    {
    for /F %%i in ('dir /b /A-D "%folder%\*"') do exit /b
    REM if you’re here, directory has no files
    call :testDIR
    exit /b
    }

    :testDIR
    for /F %%i in ('dir /b /A:D "%folder%\*"') do exit /b
    REM if you’re here, directory has no directories
    echo "%folder%" is totally empty >> list_of_empty_directories.txt
    echo Found an Empty >> list_of_empty_directories.txt
    exit /b

    :end
    echo ####checking for empty folders complete ##### >> list_of_empty_directories.txt

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>