问题
%errorlevel% doesn't work in WindowsXP.
As I know when an error occurs %errorlevel% set 1 or above value, and if there is no error it will set 0.
But, even though there is no error, %errorlevel% is 1. And I set %errorlevel% 0, even there is an error %errorlevel% is sill 0.
I think OS doesn't change %errorlevel% in XP.
In Win7 it work totally.
@echo off
setlocal enabledelayedexpansion
call dir
echo errorlevel=%errorlevel%
REM expected errorlevel=0 but 1
call dor
echo errorlevel=%errorlevel%
REM expected errorlevel=1
set errorlevel=0
call dor
echo errorlevel=%errorlevel%
REM expected errorlevel=1 but 0
But if errorlevel 1 () looks work.
回答1:
some examples for you:
@ECHO OFF &SETLOCAL
echo errorlevel=%errorlevel%
call dir >nul
echo errorlevel=%errorlevel%
output:
errorlevel=0
errorlevel=0
@ECHO OFF &SETLOCAL
echo errorlevel=%errorlevel%
call dor
echo errorlevel=%errorlevel%
output:
errorlevel=0
'dor' is not recognized as an internal or external command,
operable program or batch file.
errorlevel=1
@ECHO OFF &SETLOCAL
::set errorlevel=0 illegal operation!
set test=1
set test
echo errorlevel=%errorlevel%
call dor
echo errorlevel=%errorlevel%
output:
test=1
errorlevel=0
'dor' is not recognized as an internal or external command,
operable program or batch file.
errorlevel=1
set errorlevel
is not a legal command. If you need to set the errorlevel system environment variable, do this with a usual command.
@ECHO OFF &SETLOCAL
::set errorlevel=1 illegal operation!
set test
echo errorlevel=%errorlevel%
call dir >nul
echo errorlevel=%errorlevel%
output:
Environment variable test not defined
errorlevel=1
errorlevel=0
回答2:
It usually happens when errorlevel is manually set. It is suppossed to be a dynamic variable, but when you set it to a value, checks for its content will return not the correct errorlevel value, but the value you set to it.
If in your command line you type set errorlevel
and a variable is shown, then this is your problem. Clear the variable (set errorlevel=
) and everything will work until a value is set again.
回答3:
Besides the points stated in previous answers, you must be aware that there are certain internal commands that does not change the errorlevel value in certain cases. If in doubt, you should do a small test before assuming that the errorlevel value changed after a certain command. An easy way to set the errorlevel to 0 is using ver
command:
ver > nul
rem Here the errorlevel value is always 0
回答4:
As already mentioned in this answer, the problem in your code sample is the set errorlevel=0
.
To set the errorlevel
to any arbitrary value use:
cmd /C exit 0 & rem to set errorlevel to 0 (same as omitting the number)
cmd /C exit 1 & rem to set errorlevel to 1
来源:https://stackoverflow.com/questions/20324481/errorlevel-doesnt-work-in-windows-xp-but-it-works-in-windows7