Batch script: Search if a folder contains any files
I am trying to get a batch script to check whether a fo开发者_如何学运维lder contains any files in it. So far this is how far I have got:
IF EXIST %FILEPATH%\%%i\FromGlobus\%FILE% (
%WINZIP% %FILEPATH%\GlobusEOD\ExtraFiles\%ZIPFILE% -m %FILE%
IF errorlevel 1 goto subBADEND
)
where %FILE%
is *.*
but what happens is it tries to zip up files even when none exist and therefore fails!
Any tips or ideas?
Thank you
After some tinkering with my own scripts
A variation of @Belisarius' answer is what I've been using for awhile...After tinkering for a bit, @NimeCloud's version just doesn't seem to work on my XP machine...
I've come up with a blend of the two that seems to work for my needs:
%FOLDER%=C:\Temp
FOR /F %%i in ('dir /b "%FOLDER%\*.*"') DO ( goto :Process )
goto :Exit
:Process
...
...
...
:Exit
exit
You may use something like
set VAR=init
for /f %%a in ('dir /b c:\kk\*.*') do set VAR=exists
if %VAR%==exists ...
Not very efficient in case of large directories, but it works.
HTH!
dir . returns . .. maybe these virtual dirs cause the mess. You could try FIND pipe like below:
SET filter=*.*
SET notfound="File not found"
DIR %filter% | FIND %notfound%
@If ErrorLevel 1 Goto :end
If you use /A:-D
for dir
command, then it will switch the return code if directory has files. Works only for files (/A:D
won't work for subdirectories in the same way)
dir /A:-D /B "mydir" >nul 2>nul && echo.mydir having files
You could use find
with dir
to ensure the return code matches what you'd expect when no files are found:
DIR /A /B | >NUL FIND /V "" && ECHO Folder contains files || ECHO Folder empty
精彩评论