What is the easiest way to reset ERRORLEVEL to zer

2019-01-13 14:38发布

I have a post-build event that runs some commands for a c# project. The last command would sometimes cause the ERRORLEVEL value not equals to zero and then the build fails.

I want to append an extra line of command to always set the ERRORLEVEL value to zero. What is the most convenient way to do that?

10条回答
The star\"
2楼-- · 2019-01-13 14:58

If this is a snippet like "Post-build Event" etc., then you'll be fine appending:

(...) || ver > nul

at the end of the last command.

Alternatively

cmd /c "exit /b 0"

is very clean and non-idiomatic -- a reader who knows Windows shell will know what's going on, and what was your intent.

However, if you're in a batch script, you may want to use subrotines, which are a lightweight equivalent of the "child batch script" from akf's answer.

Have a subroutine:

:reset_error
exit /b 0

and then just

call :reset_error

wherever you need it.

Here's a complete example:

@echo off
rem *** main ***

call :raise_error
echo After :raise_error ERRORLEVEL = %ERRORLEVEL%

call :empty
echo After :empty ERRORLEVEL = %ERRORLEVEL%

call :reset_error
echo After :reset_error ERRORLEVEL = %ERRORLEVEL%

:: this is needed at the end of the main body of the script
goto:eof

rem *** subroutines ***

:empty
goto:eof

:raise_error
exit /b 1

:reset_error
exit /b 0

Which outputs:

After :raise_error ERRORLEVEL = 1
After :empty ERRORLEVEL = 1
After :reset_error ERRORLEVEL = 0

As you see - just calling and returning via goto:eof is not enough.

查看更多
我只想做你的唯一
3楼-- · 2019-01-13 15:04

I found that "exit 0" looks like a good way to deal with this problem.

Usage Example:

NET STOP UnderDevService /Y

exit 0

if the UnderDevService service is not started.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-13 15:10

I'm using this:

ping localhost -n 1 >null

查看更多
戒情不戒烟
5楼-- · 2019-01-13 15:12

I personally use this:

cd .

Works even in unix shell.

But, this one might be a bit faster:

type nul>nul

Because Process Monitor shows QueryDirectory calls on cd .

PS: cd . has another nice side effect in the unix shell. It does restore recreated working directory in the terminal if it has been opened before the erase.

查看更多
够拽才男人
6楼-- · 2019-01-13 15:14

Seems to do the trick:

ver > nul

Not everything works, and it is not clear why. For example, the following do not:

echo. > nul
cls > nul
查看更多
Lonely孤独者°
7楼-- · 2019-01-13 15:14

I use VERIFY or VERIFY > nul

查看更多
登录 后发表回答