I am new to batch scripting and while fiddling with the simple ones in my Windows 7 pc, I stuck on the following -
command1
echo %errorlevel%
if %errorlevel% neq 0 (
echo -- Error occured during command1 execution ---
goto :eof
) else (
echo -- command1 execution was successful ---
command2
echo %errorlevel%
if %errorlevel% neq 0 (
echo -- Error occured during command2 execution ---
goto :eof
)
)
Here, command1 excution is successful(checked separately) and it is returning errorlevel 0(success) while command2 is failing(checked separately) and instead of no zero (failure) it is returning errorlevel as 0. But when I remove else condition, command2 execution is returning 1 (failure). Curious to know the reason.
As suggested, now I am declaring setlocal enabledelayedexpansion at the begining and instead of %errorlevel%, using !errorlevel! and it is giving desired errorlevel on success/failure.
But now I am facing another problem. I am calling another command (suppose command3 in place of command2). It inturn calls one of my java class which is throwing java.lang.StringIndexOutOfBoundsException. But in my .bat file it is returning errorlevel as 0, instead of 1 whereas command3 got failed (checked seperately). Below is my latest script -
@echo off
setlocal enabledelayedexpansion
command1
echo call !errorlevel!
if !errorlevel! neq 0 (
echo -- Error occured during command1 execution ---
goto :eof
)
echo -- command1 execution was successful ---
REM command3
java MyclassName > logfilename.log 2>&1
echo call !errorlevel!
if !errorlevel! neq 0 (
echo -- Error occured during command3 execution ---
goto :eof
)
echo --- command3 Executoin was successful---
How to force !errorlevel! to return correct value when it is failed with some exception. Please help.
setlocal enabledelayedexpansionis the key here. where is the rest of the script? - Gerhard