Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In a batch file, I have an inconsistent errorlevel behavior:

The following code always gives errorlevel 0 in one location (somewhere in the middle - exactly where i need it) inside the batch file.

I copied only this snippet and placed it in the beginning and at the end of the batch file. In those locations, the result is always 1.

Here is the code snippet:

dir c:\

IF ERRORLEVEL 1 echo ERRORLEVEL is 1 or more

Any idea how to make it work also in the middle of the file? What am I doing wrong? I would hate to solve it with GOTOs(to the end of the file and back to where I need the result.)

share|improve this question
The whole ping issue was unrelated to the errorlevel question, so I replaced it with a 'dir' command. – Doron Mar 30 '12 at 9:36
Please provide us with a code snippet that demonstrates fully the inconsistent behaviour – Iain Apr 16 '12 at 7:17


You are confusing the command interpreters ERRORLEVEL return value and the environment variable ERRORLEVEL. When a command runs it sets the ERRORLEVEL value not the environment variable value. You can interrogate the return value using the


command which returns true if the ERRORLEVEL return value is n or higher e.g.

dir C:\

<directory listing omitted>

IF ERRORLEVEL 1 echo ERRORLEVEL is 1 or more

would print nothing whereas

dir C:\somenonexistentdir

File Not Found

IF ERRORLEVEL 1 echo ERRORLEVEL is 1 or more
ERRORLEVEL is 1 or more

the message is printed. My guess is that you are setting the value of %ERRORLEVEL% in your script and expecting later return values to overwrite this. As %ERRORLEVEL% is not ERRORLEVEL this doesn't happen.

share|improve this answer
dir c:\ set %errorlevel% to 0 – Doron Apr 2 '12 at 9:24
dir nonexistentdir set %errorlevel% to 1 – Doron Apr 2 '12 at 9:25
What am I missing here? – Doron Apr 2 '12 at 9:25
Don't query %ERRORLEVEL% – Iain Apr 2 '12 at 9:28
OIC %ERRORLEVEL% was replaced as a fallback with error level – Doron Apr 2 '12 at 10:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.