You are not logged in.
How do I find an error in the for loop if there is no directory found?
ex.
for /f "tokens=*" %%a in ('dir "%cd%" /a:d /b 2^> nul') do (
echo %%a
)
%errorlevel% always is 0
Please help me
Last edited by PiotrMP006 (23 Dec 2019 07:25)
Offline
@echo off
SET cd=[put the directory path here]
REM Define the command line to be executed
SET cline=DIR "%cd%" /A:D /B
echo: & echo Directory: %cd%
REM Count the number of subdirectories
SET "nDirs=0" & FOR /F %%G IN ('%cline%') DO SET /A "nDirs+=1"
echo: & echo Number of subdirectories: %nDirs%
REM Display the subdirectory names
IF %nDirs% GEQ 1 (echo: & echo Subdirectory listing: & echo: & %cline%)
echo: & Pause
EXIT
Offline
Could also check for the parent directory as follows.
@echo off
SET cd=[Set directory here]
echo: & echo Directory: %cd% & echo:
IF EXIST "%cd%" (SET cline=DIR "%cd%" /A:D /B) ELSE (echo ERROR: Directory was not found. & GOTO done)
REM Display the number of subdirectories
SET "nDirs=0" & FOR /F %%G IN ('%cline%') DO SET /A "nDirs+=1"
echo Number of subdirectories: %nDirs%
REM Display the subdirectory names
IF %nDirs% GEQ 1 (echo: & echo Subdirectory listing: & echo: & %cline%)
:done
echo: & Pause
EXIT
Offline
@echo off
title directory count.
SET count=1
FOR /f "tokens=*" %%G IN ('DIR "%cd%" /A:D /B') DO (
call :litr %%G
)
if defined NumberFiles (
if %NumberFiles% NEQ 0 (
echo Counted %NumberFiles% in %cd%
) else (
echo Counted %NumberFiles% in %cd%
)
) else (
echo Counted 0 files in %cd%
)
echo done.
pause
exit /b
:litr
Set "NumberFiles=%count%"
set /a count+=1
exit /b %NumberFiles%
in this case you can also use %errorlevel% to verify the number of counted files.
Offline
try this:
(for /f "tokens=*" %%a in ('dir "%cd%" /a:d /b 2^> nul') do @(echo %%a)) || echo error
all error in dir command will be trap on sentence after or operator ||
cmd|ps|rexx|ada|C|C++|C#|vba|java|js|rpg|cobol|mih|perl|al
Offline