Windows if errorlevel 1

Windows if errorlevel 1

Performs conditional processing in batch programs.

Syntax

If command extensions are enabled, use the following syntax:

Parameters

Parameter Description
not Specifies that the command should be carried out only if the condition is false.
errorlevel Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
Specifies the command that should be carried out if the preceding condition is met.
== Specifies a true condition only if string1 and string2 are the same. These values can be literal strings or batch variables (for example, %1 ). You do not need to enclose literal strings in quotation marks.
exist Specifies a true condition if the specified file name exists.
Specifies a three-letter comparison operator, including:
  • EQU — Equal to
  • NEQ — Not equal to
  • LSS — Less than
  • LEQ — Less than or equal to
  • GTR — Greater than
  • GEQ — Greater than or equal to
/i Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2 are comprised of numeric digits only, the strings are converted to numbers and a numeric comparison is performed.
cmdextversion Specifies a true condition only if the internal version number associated with the command extensions feature of Cmd.exe is equal to or greater than the number specified. The first version is 1. It increases by increments of one when significant enhancements are added to the command extensions. The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined Specifies a true condition if variable is defined.
Specifies a command-line command and any parameters to be passed to the command in an else clause.
/? Displays help at the command prompt.

Remarks

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause.

When a program stops, it returns an exit code. To use exit codes as conditions, use the errorlevel parameter.

If you use defined, the following three variables are added to the environment: %errorlevel%, %cmdcmdline%, and %cmdextversion%.

%errorlevel%: Expands into a string representation of the current value of the ERRORLEVEL environment variable. This variable assumes that there isn’t already an existing environment variable with the name ERRORLEVEL. If there is, you’ll get that ERRORLEVEL value instead.

%cmdcmdline%: Expands into the original command line that was passed to Cmd.exe prior to any processing by Cmd.exe. This assumes that there isn’t already an existing environment variable with the name CMDCMDLINE. If there is, you’ll get that CMDCMDLINE value instead.

%cmdextversion%: Expands into the string representation of the current value of cmdextversion. This assumes that there isn’t already an existing environment variable with the name CMDEXTVERSION. If there is, you’ll get that CMDEXTVERSION value instead.

You must use the else clause on the same line as the command after the if.

Examples

To display the message Cannot find data file if the file Product.dat cannot be found, type:

To format a disk in drive A and display an error message if an error occurs during the formatting process, type the following lines in a batch file:

To delete the file Product.dat from the current directory or display a message if Product.dat is not found, type the following lines in a batch file:

These lines can be combined into a single line as follows:

To echo the value of the ERRORLEVEL environment variable after running a batch file, type the following lines in the batch file:

To go to the okay label if the value of the ERRORLEVEL environment variable is less than or equal to 1, type:

windows batch errorlevel with if

In the below script even if errorlevel is 0, Its going to if condition «if errorlevel 1»

2 Answers 2

OR, preferably since you have invoked delayedexpansion ,

With your current code, the entirity from

if not errorlevel 1 (

to the single ) before the endlocal line is one block statement .

Within a block statement (a parenthesised series of statements) , the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable’s value at the time the block is parsed — before the block is executed — the same thing applies to a FOR . DO (block) .

Hence, since the block starts with

then %errorlevel% will be replaced by the value of errorlevel at the time the if is encountered, that is 0 , so your echo will be replaced by echo error code is:0

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var . CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

note that last statement

CALL ECHO %%errorlevel%%` displays, but sadly then RESETS errorlevel.

So your errorlevel would now be displayed correctly, but would be reset to 0 by the call .

ERRORLEVEL это не %ERRORLEVEL% [Статья]

Мои комментарии к статье с примерами:

Да, действительно. Отключаем расширения для команд и переменная ErrorLevel уже не раскрывается в код возврата ошибки:

Полезняшка:
Поскольку ErrorLevel — является командой, а не переменной.
Для ее работы не требуется использовать отложенное расширение переменных среды.
Значит, в циклах, под скобками или в однострочной команде можно писать просто:

Общая идея — да. А вот пример работает не совсем так, как Вы предполагаете из вышесказанных слов.
Дело в том, что сама команда set тоже возвращает после своего выполнения код возврата. Он = 0.
Проверим?

В ответ ничего не получим. Т.к. настоящий код возврата (не переменная) = 0.

1) Переменная %ERRORLEVEL% и код возврата ошибки — это не всегда одно и тоже.

2) IF ERRORLEVEL N — это команда, которая дает TRUE, если код возврата ошибки при выполнении предыдущей команды >= N, где N — это число (не переменная).

3) Если включен режим расширения для команд (а он включен по-умолчанию), то
%errorlevel% = сначала процессор смотрит определена ли переменная, иначе получает код возврата ошибки.

4) Такие команды как if, echo. не влияют на код ошибки.

5) Командой ErrorLevel удобно сравнивать код возврата ошибки внутри скобок, циклов, однострочной команде,
т.к. не нужно использовать конструкцию !errorlevel!, а это дает дополнительный прирост в скорости работы.

6) Конструкции вида if %errorlevel%==0 нужно использовать с осторожностью, т.к. отключенный в реестре пользователя режим расширения команд приведет к падению работы скрипта.
Обязательно используйте кавычки: if «%errorlevel%»==»0» или не забывайте принудительно включать директиву SetLocal EnableExtensions в пакетный файл.

Проверка %ERRORLEVEL%
Добрый день! Помогите пожалуйста. После запуска команды необходимо сделать проверку %ERRORLEVEL%.

Обработка значения ERRORLEVEL
есть скриптик, кусок его прилагаю errorlevel выдает 17, хотя должен по моему мнению 1.

Обработка значения ERRORLEVEL
Привет всем! Столкнулся с проблемой обработки значения errorlevel. Вызываю внешний скрипт call.

%ERRORLEVEL% в Windows Embedded CE 6.0
@echo off set count=0 :begin set /A count=count+1 ping localhost -n 10 ping -n 1 -w 3000.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Получение ERRORLEVEL команды TASKKILL
Здравствуйте. В системе периодически запускается скрипт, работа которого занимает определенное.

Коды возврата ошибок (расшифровки ErrorLevel)*
Коды возврата ошибок (встроенных команд и других программ) Для новичков — очень подробно.

Errorlevel 9009 при выполнении dsmod
при выполнении: set login=%username% for /f «delims=xxx» %%a in (‘findstr %login%.

Вывести текст ошибки по значению errorlevel в bat
Добрый день, товарищи! Появилась необходимость записывать в log-файлы сообщения об ошибках. Типа.

IF, CALL, EXIT and %ERRORLEVEL% in a .bat

Can anyone please help me understand the behaviour of %ERRORLEVEL% variable and why it’s not being set after a CALL while being inside an IF , i.e. the ECHO %ERRORLEVEL%.2 line?

STDOUT

However, without IF the %ERRORLEVEL% variable is set as expected.

STDOUT

2 Answers 2

When the cmd parser reads a line or a block of lines (the code inside the parenthesis), all variable reads are replaced with the value inside the variable before starting to execute the code. If the execution of the code in the block changes the value of the variable, this value can not be seen from inside the same block, as the read operation on the variable does not exist, it was replaced with the value in the variable

To solve it, you need to enable delayed expansion, and, where needed, change the syntax from %var% to !var! , indicating to the parser that the read operation needs to be delayed until the execution of the command.

MC ND answered the question already well.

Here is an alternative code showing both: expanded and delayed expansion of ERRORLEVEL.

Microsoft describes the behavior of delayed expansion in help of command set which can be read in a command prompt window after entering set /? or help set

Not the answer you’re looking for? Browse other questions tagged windows batch-file or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Set errorlevel in Windows batch file

I am writing a batch script that will loop through each line of a text file, (each line containing a filename) check if the file exists and then runs the file and moves it.

Here is my batch script:

Here is the output:

I do not understand why the «if errorlevel» is not working as expected. if the file does not exist (as in this example where it does not exist) it should NOT try to run the file, it should NOT copy the file, and it should echo a 2 not a 0

Edit 1: I was reading another SO Post regarding «delayed environment variable expansion» I am not sure if this issue is related

4 Answers 4

Here’s a rewritten procedure.

Note: output.txt is deleted at the start, else the >> would append to any existing file. 2>nul suppresses error messages if the delete fails (eg. file not exist)

Within a block statement (a parenthesised series of statements) , the ENTIRE block is parsed and THEN executed. Any %var% within the block will be replaced by that variable’s value AT THE TIME THE BLOCK IS PARSED — before the block is executed.

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the chnaged value of var or 2) to call a subroutine to perform further processing using the changed values.

Note therefore the use of CALL ECHO %%var%% which displays the changed value of var . CALL ECHO %%errorlevel%% displays, but sadly then RESETS errorlevel.

IF DEFINED var is true if var is CURRENTLY defined.

ERRORLEVEL is a special varable name. It is set by the system, but if set by the user, the user-assigned value overrides the system value.

IF ERRORLEVEL n is TRUE if errorlevel is n OR GREATER THAN n. IF ERRORLEVEL 0 is therefore always true.

The syntax SET «var=value» (where value may be empty) is used to ensure that any stray spaces at the end of a line are NOT included in the value assigned.

The required commands are merely ECHO ed for testing purposes. After you’ve verified that the commands are correct, change ECHO COPY to COPY to actually copy the files.

I used the following input.txt :

With existing files seterr*.bat which contain

(where the 1 in the last line determines the errorlevel returned)

and received the resultant output:

Note that the COPY is merely ECHO ed as I mentioned earlier.

Читайте также:  Просмотр дискового пространства windows
Оцените статью