It is possible to get the %ERRORLEVEL%
with for /f
, as aschipfl
pointed it out in the comments, but it is tricky, I found this
on dostips.com forum and now I get the error number from the command so using that code as base I did something like this:
@echo off
setlocal EnableDelayedExpansion
for /f "tokens=*" %%i in ('%command% ^|^| call echo ERROR_NUMBER%%^^^^errorlevel%%') do (
set OutputLine=%%i
if /i "!OutputLine:~0,12!" == "ERROR_NUMBER" (
set ERRNB=!OutputLine:ERROR_NUMBER=!
echo The error number was: !ERRNB!
)
)
Note that I'm using EnableDelayedExpansion
, the %command%
it's just the command that will be executed, ^|^|
to escape the pipes
characters and is executed when the previous command fails and the rest is a way to get the error number in %%^^^^errorlevel%%
in the dostips.com forum Dave Benham
says it's just a hack
:
It is not really escaping anything. It is a hack that postpones the
expansion of the variable.
Remember that in a command line context, the result of %DoesNotExist%
is %DoesNotExist%. Also remember that a caret before any character
results in that character being preserved. It doesn't have to be a
special character.
The caret is treated as part of the variable name during the expansion
phase. So lets say we have a variable named "myVar". Then a command
line statement like call echo %^myVar%, tries to expand the variable
"%^myVar%" before the CALL, but it doesn't exist. The caret is then
removed (the m is preserved), and you are left with %myVar%. Then
after the CALL it tries again and properly expands the properly named
variable.
Of course the above will fail if a variable named "^myVar" exists. But
carets are not normally used in variable names.
Dave Benham
('command')
is executed in a separate process. This should answer your question. (Hint: errorlevel is lost, when the process ends) – Coofor
loop). Alternative:%SQLCommand% > output.txt
andif %errorlevel% == 1 for /f "tokens=*" %%i in (output.txt) do ( ...
– Coofor /F %%L in ('%SQLCommand% ^& call echo %%^^ErrorLevel%%') do ( ... )
could perhaps be used to capture theErrorLevel
as well (although I'm not sure whether I appied escaping correctly as I can't test right now)... – Guideline