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?
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
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With