You are not logged in.

#1 23 Dec 2019 07:24

PiotrMP006
Member
Registered: 02 Apr 2019
Posts: 12

How do I find an error in the for loop if there is no directory found?

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

#2 29 Aug 2020 18:26

mikeyww
Member
Registered: 29 Aug 2020
Posts: 5

Re: How do I find an error in the for loop if there is no directory found?

@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

#3 29 Aug 2020 18:38

mikeyww
Member
Registered: 29 Aug 2020
Posts: 5

Re: How do I find an error in the for loop if there is no directory found?

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

#4 29 Aug 2020 20:20

kabue murage
New Member
Registered: 29 Aug 2020
Posts: 1

Re: How do I find an error in the for loop if there is no directory found?

@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

#5 15 Oct 2020 14:53

tra
Member
From: Andorra
Registered: 15 Oct 2020
Posts: 6

Re: How do I find an error in the for loop if there is no directory found?

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

Board footer

Powered by