0

I have a bat-file with 10 reg commands. I need bat-file at the end of its work display a message if at least 1 error is occurred and pause.

I have read this manuals http://ss64.com/nt/if.html http://ss64.com/nt/errorlevel.html and they are completely unclear. As I see there are 2 variables ERRORLEVEL - system and local. But in many stackoverflow answers both variables are used: How do I make a batch file terminate upon encountering an error? check if command was successfull in a batch file So if some application return some code simultaneously with bat-file I can get wrong behaviour. So I need local ERRORLEVEL. What should I do?

Community
  • 1
  • 1

1 Answers1

2

Note of caution by @dbenham:

It is possible for a user to set an ERRORLEVEL environment variable that overrides the intended dynamic %ERRORLEVEL% value. See this for more information.

So unless you do strange things like manually assigning to errorlevel, there is only one errorlevel variable and it is set locally for the currently executed batch file by the last executed command in your batch file. It's called a system variable only because it's set by system, not by you, the user.

setlocal enableDelayedExpansion
reg do something1 || set error=, 1
reg do something2 || set error=!error!, 2
reg do something3 || set error=!error!, 3

if not "!error!"="" echo Failed tasks: !error:~2!
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • `set error=, 1` assigns `, 1` to the variable `error` and `set error=!error!, 2` sets it to the previous value plus `, 2`. At the end of execution the first two characters are stripped: `!error:~2!`. Exclamation marks are used instead of `%` because of [enableDelayedExpansion](http://ss64.com/nt/delayedexpansion.html). – wOxxOm Jul 27 '15 at 17:44
  • Um. ", 1" is a string or what? If this is string , where are quote marks? If this is not a string , what comma means? – testnameC04 Jul 27 '15 at 17:51
  • Batch file syntax [does not require quotes](http://ss64.com/nt/set.html) for strings in `set` assignments. The comma is added for the reasons I've stated above - the first two characters are stripped in the end. – wOxxOm Jul 27 '15 at 17:55
  • +1, Your code is fine, but your explanation is a bit misleading, given that it is possible for a user to set an ERRORLEVEL environment variable that overrides the intended dynamic `%ERRORLEVEL%` value. See http://blogs.msdn.com/b/oldnewthing/archive/2008/09/26/8965755.aspx for more information. This is a tricky topic. – dbenham Jul 27 '15 at 18:58
  • Thanks for the info, I've included your note in the answer if you don't mind. – wOxxOm Jul 27 '15 at 19:18