Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How execute a command in batch-file if errorlevel is not zero?

I created a simple batch file which would enable me to connect to the internet.
I made it this way- If the connection is successful a message is displayed stating "connection successful" using VBscript and display a message stating "connection failure" if the connection is not established. I made this using if-else statements and errorlevel command, but I am not able to display the failure message using 'errorlevel == 1' command.I mean that if there was an error in the connection process the success message is displayed instead of failure message.

Here's the code in my batch file.

rasdial "TATA PHOTON+" internet

@echo off
if ERRORLEVEL == 0 (echo MSGBOX "Connection successfully established to TATA PHOTON+" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q)
else if ERRORLEVEL == 1 (echo MSGBOX "ERROR: Unable to establish connection" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
)
like image 930
Swaroop Avatar asked Sep 03 '25 09:09

Swaroop


2 Answers

Try something like that :

rasdial "TATA PHOTON+" internet
@echo off
IF %ERRORLEVEL% EQU 0 (
    Goto :sucess
) else (
    GoTo :Fail
)
::****************************************************************************************
:sucess
(echo MSGBOX "Connection successfully established to TATA PHOTON+",VbInformation,"Connection successfully established to TATA PHOTON+" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
)
Exit /b
::****************************************************************************************
:Fail
(echo MSGBOX "ERROR: Unable to establish connection",vbCritical,"ERROR: Unable to establish connection" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
)
Exit /b
::****************************************************************************************
like image 169
Hackoo Avatar answered Sep 04 '25 23:09

Hackoo


The line

if errorlevel == 0 do-something

is not valid syntax. Based on some quick tests, it would appear that the command processor is reinterpreting it as

if errorlevel 0 do-something

which means "if errorlevel is at least 0 do something".

Instead, I recommend

if %ERRORLEVEL% EQU 0 do-something

Using the percent-signs version allows you to test for equality and also correctly handles the case where the return value is negative.

like image 34
Harry Johnston Avatar answered Sep 05 '25 00:09

Harry Johnston