I'm trying to automate a program I made with a test suite via a .cmd file.
I can get the program that I ran's return code via %errorlevel%.
My program has certain return codes for each type of error.
For example:
1 - means failed for such and such a reason
2 - means failed for some other reason
...
echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt
Instead I'd like to somehow say:
echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt
Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?
It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.
BAT is the batch file that is used in DOS, OS/2 and Microsoft Windows. CMD files are newer version came into existence for batch files. The older systems will not know about CMD files and will run them partially which will throw an error for the batch files saved as CMD.
Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.
You can do this quite neatly with the ENABLEDELAYEDEXPANSION
option. This allows you to use !
as variable marker that is evaluated after %
.
REM Turn on Delayed Expansion
SETLOCAL ENABLEDELAYEDEXPANSION
REM Define messages as variables with the ERRORLEVEL on the end of the name
SET MESSAGE0=Everything is fine
SET MESSAGE1=Failed for such and such a reason
SET MESSAGE2=Failed for some other reason
REM Set ERRORLEVEL - or run command here
SET ERRORLEVEL=2
REM Print the message corresponding to the ERRORLEVEL
ECHO !MESSAGE%ERRORLEVEL%!
Type HELP SETLOCAL
and HELP SET
at a command prompt for more information on delayed expansion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With