[Solved] How to create a batch file that checks if EXACTLY four specific files/folders exist in a folder?


Here is a method. We first count the files, then we test the files.

@echo off & set cnt=0
for /f %%i in ('dir /b') do set /a cnt+=1
if %cnt% equ 4 if exist f1 if exist f2 if exist dir1 if exist dir2 echo All Good!

and some light error generations:

@echo off & set cnt=0
for /f %%i in ('dir /b ^| findstr /v "%0"') do set /a cnt+=1
if not %cnt% equ 4 echo oops, too many files/dirs, I count %cnt% && goto :eof
if exist f1 if exist f2 if exist dir1 if exist dir2 echo All good && goto :eof
echo one or more files do not match your if statement

and one last method using find to not utilize a for loop.

@echo off
dir /b | find /c /v "" | findstr "\<4\>"
if errorlevel 1 echo oops, too many files/dirs, I count %cnt% && goto :eof
if exist f1 if exist f2 if exist dir1 if exist dir2 echo All good && goto :eof
echo one or more files do not match your if statement

Notes taken from this answer’s comments:

  1. @echo off & set cnt=0 are integrated into a single line just to reduce the number of lines. No other reason.
  2. findstr /v "%0" is only needed if the batch file itself could be in the same folder, as that command simply excludes the batch file itself as part of the file count.

0

solved How to create a batch file that checks if EXACTLY four specific files/folders exist in a folder?