Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if folder is not empty (Windows Batch File)?

Using a simple batch file, compatible with the command processor in Windows 7, how can one detect if a folder has any contents (meaning one or more files or subfolders, i.e. not empty)?

I tried:

IF EXIST C:\FOLDERNAME\* GOTO ROUTINE

But this always returns TRUE and thus goes to ROUTINE.

How can this be accomplished?

like image 277
RockPaperLz- Mask it or Casket Avatar asked Apr 14 '17 09:04

RockPaperLz- Mask it or Casket


Video Answer


2 Answers

dir /A /B "C:\FOLDERNAME" | findstr /R ".">NUL && GOTO ROUTINE

If there is at least one line of output, then the directory is not empty.
The findstr /R "." results the into a successful exitcode and the && will execute the goto routine

like image 56
user2956477 Avatar answered Sep 29 '22 13:09

user2956477


The solution I prefer is to iterate through the files in the directory and then iterate through the attributes of each file to get its size and find out if it is greater than 0.

The following script I made validates the following:

  • If the specified directory exists.
  • Whether the folder contains files or not.
  • If the folder contains files larger than 0 bytes.

In case there are no files or the files do not exceed 0 bytes, the script will report that the directory does not contain any files.

To run the script you must use the following command, where "C:/path" is the directory to check:

start name.bat "C:/path"

Rename the script and change the directory.


Bat script:

@echo off

REM Command to launch the script:
REM >> start name.bat "C:/path"

REM Check if path exist
if exist %1 (

    REM Loop in dir files
    for /f "delims=" %%f in ('dir /a /b /s %1') do (
        
        REM Check file sizes
        for /f "usebackq delims=" %%s in ('%%f') do (

            REM Check if there is a file bigger than 0 bytes
            if %%~zs GTR 0 (
                echo The directory is not empty
                goto end
            )
        )
    )
    echo The directory is empty

) else (
    echo The directory does not exist
)

:end
pause
like image 27
Ariel Montes Avatar answered Sep 29 '22 14:09

Ariel Montes