0

I'm facing an issue when trying to implement the ERRORLEVEL on my batch script. Basically what I'm trying to do is: look for the .txt files in the directory and if found; .txt will get listed, if not found; message error will occur.

The thing is that this directory will not always contain a .txt, sometimes it will be empty and when that happens my code will not work. Only when there is a .txt in the directory I'm getting my conditions to work (ERRORLEVEL = 0), but if empty; none of my conditions will. Not even the ERRORLEVEL will be printed in the cmd screen (I should see it as ERRORLEVEL = 1).

This is my code:

for /r "C:\Texts" %%a in (*.txt) do ( 
echo %errorlevel%
IF ERRORLEVEL 0 (    
    echo %%a
    echo "I found your Text!"
    ) ELSE (
        echo "I couldn`t find your Text!" )
    )

What exactly is wrong with my ERRORLEVEL implementation?

ted
  • 13,596
  • 9
  • 65
  • 107
  • 1
    Take a look at [Delayed Expansion](http://ss64.com/nt/delayedexpansion.html). But it also looks like you forgot a find command. – wimh Aug 01 '15 at 22:37
  • I think you might find this answer: http://stackoverflow.com/a/3942468/221005 helpful. – Beel Aug 01 '15 at 22:40

2 Answers2

0

Errorlevel 0 is always true.

Use

if not errorlevel 1

But your code doesn't set the errorlevel.

foxidrive
  • 40,353
  • 10
  • 53
  • 68
0

In your code there is not any command that set the errorlevel. This value is set by all external .exe commands (like find or findstr), and by certain specific internal commands (like verify that set errorlevel=1 when its parameter is wrong, or ver that always set the errorlevel=0.

You may explicitly set this value in your code this way:

rem Set the errorlevel to 1
verify bad 2> NUL

for /r "C:\Texts" %%a in (*.txt) do (
   echo %%a
   rem Set the errorlevel to 0
   ver > NUL
)

if not ERRORLEVEL 1 (
   echo "I found your Text!"
) else (
   echo "I couldn't find your Text!"
)

However, you may also get a similar result using a Batch variable instead of the errorlevel...

Aacini
  • 65,180
  • 12
  • 72
  • 108