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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
PiotrMP006
Posts: 29
Joined: 08 Sep 2017 06:10

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

#1 Post by PiotrMP006 » 23 Dec 2019 01:38

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

ex.

Code: Select all

for /f "tokens=*" %%a in ('dir "%cd%" /a:d /b 2^> nul') do (
echo %%a
)
%errorlevel% always is 0

Please help me

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

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

#2 Post by aGerman » 23 Dec 2019 05:30

The command line enclosed in single quotes runs in a separate cmd.exe process. That's the reason why you can't get the errorlevel.
If you don't have subfolders in %cd% the loop body is never executed. You may use a helper variable.

Code: Select all

set "folders_present="
for /f "tokens=*" %%a in ('dir "%cd%" /a:d /b 2^> nul') do (
  set "folders_present=1"
  echo %%a
)
if not defined folders_present echo No folder found.
Steffen

Post Reply