Reputation: 1611
Hello I'm looking to write a batch file to check to see if there are any files of any type inside a given folder.
So far I've tried the following
if EXIST FOLDERNAME\\*.* ( echo Files Exist ) ELSE ( echo "Empty" )
I can get it to work if I know the file extension such as a txt file with the follwing
if EXIST FOLDERNAME\\*.txt ( echo Files Exist ) ELSE ( echo "Empty" )
Thank you for your help
Upvotes: 39
Views: 122243
Reputation: 2293
A roll your own function.
Supports recursion or not with the 2nd
switch.
Also, allow names of files with ;
which the accepted answer fails to address although a great answer, this will get over that issue.
The idea was taken from https://ss64.com/nt/empty.html
Notes within code.
@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written: 2020.01.26
:: Posted on the thread here: https://stackoverflow.com/q/10813943/8262102
:: Based on: https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>" = Your path wrapped in quotes.
:: <BOOLEAN> = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE = if directory doesn't exist.
:: 0-inf = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
) else if not "%~1"=="" (
set count=0 & set msg= & set dirExists=
if not exist "!%~1!" (set msg=FALSE)
if exist "!%~1!" (
if {%~2}=={TRUE} (
>nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
set msg=!count!
)
if {%~2}=={FALSE} (
for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
set msg=!count!
)
)
)
set "%~1=!msg!" & goto :eof
)
Upvotes: 0
Reputation: 163
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
Upvotes: 13
Reputation: 130859
To check if a folder contains at least one file
>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder or any of its descendents contain at least one file
>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder contains at least one file or folder.
Note addition of /a
option to enable finding of hidden and system files/folders.
dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)
To check if a folder contains at least one folder
dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)
Upvotes: 57