Batch file .cmd和.bat文件将返回代码转换为错误消息

Batch file .cmd和.bat文件将返回代码转换为错误消息,batch-file,cmd,build-automation,Batch File,Cmd,Build Automation,我正试图通过一个.cmd文件自动化我用测试套件制作的程序 我可以通过%errorlevel%获取我运行的程序的返回代码 我的程序对每种类型的错误都有特定的返回码 例如: 1-指因某种原因而失败 2-表示由于其他原因失败 echo失败:测试用例失败,错误级别:%errorlevel%>>TestSuite1Log.txt 相反,我想说: echo失败:测试用例失败,错误原因:lookupError(%errorlevel%)>>TestSuite1Log.txt 使用.bat文件可以这样做吗?或

我正试图通过一个.cmd文件自动化我用测试套件制作的程序

我可以通过%errorlevel%获取我运行的程序的返回代码

我的程序对每种类型的错误都有特定的返回码

例如:

1-指因某种原因而失败

2-表示由于其他原因失败

echo失败:测试用例失败,错误级别:%errorlevel%>>TestSuite1Log.txt

相反,我想说:

echo失败:测试用例失败,错误原因:lookupError(%errorlevel%)>>TestSuite1Log.txt


使用.bat文件可以这样做吗?或者我必须使用python/perl这样的脚本语言吗?

不完全是这样,有一个子例程,但是您可以使用变通方法用文本填充变量


如果您的这个测试套件增长了很多以使用更强大的语言,那么可能会更容易。Perl甚至Windows脚本主机都可以在这方面帮助您。

是的,您可以使用call。刚接到一个新的电话,打个电话,然后输入错误代码。这应该行得通,但我还没有测试

C:\Users\matt.MATTLANT>help call
Calls one batch program from another.

CALL [drive:][path]filename [batch-parameters]

  batch-parameters   Specifies any command-line information required by the
                     batch program.

SEDIT:对不起,我可能有点误解了,但是你也可以使用IF来反向测试你的值,并使用IF的重载行为:

@echo off
myApp.exe
if errorlevel 2 goto Do2
if errorlevel 1 goto do1
echo Success
goto End

:Do2
echo Something when 2 returned
goto End

:Do1
echo Something when 1 returned
goto End

:End
如果您想变得更强大,可以尝试类似的方法(您需要将%1替换为%errorlevel,但这对我来说更难测试)。您需要为处理的每个错误级别贴上标签:

@echo off
echo passed %1
goto Label%1

:Label
echo not matched!
goto end

:Label1
echo One
goto end

:Label2
echo Two
goto end

:end
下面是一个测试:

C:\>test
passed
not matched!

C:\>test 9
passed 9
The system cannot find the batch label specified - Label9

C:\>test 1
passed 1
One

C:\>test 2
passed 2
Two

您可以使用“IF ERRORLEVEL”语句根据返回代码执行不同的操作

见:


在回答你的第二个问题时,我会转而使用脚本语言,因为Windows批处理文件本身就非常有限。Perl、Python、Ruby等都有很好的Windows发行版,所以没有理由不使用它们。我个人喜欢在Windows上编写Perl脚本。

您可以执行以下代码。请注意,由于cmd异常,错误级别比较应按降序进行

setlocal

rem Main script
call :LookupErrorReason %errorlevel%
echo FAILED Test case failed, error reason: %errorreason% >> TestSuite1Log.txt
goto :EndOfScript

rem Lookup subroutine
:LookupErrorReason
  if %%1 == 3 set errorreason=Some reason
  if %%1 == 2 set errorreason=Another reason
  if %%1 == 1 set errorreason=Third reason
goto :EndOfScript

:EndOfScript
endlocal

使用
ENABLEDELAYEDEXPANSION
选项可以非常灵活地完成此操作。这允许您使用
作为变量标记,在
%
之后计算

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%!

在命令提示符下键入
HELP SETLOCAL
HELP SET
,以获取有关延迟扩展的详细信息。

我喜欢这一点的简单性,我的回答可以追溯到很久以前的DOS。什么时候添加了ENABLEDELAYEDEXPANSION选项?哦,需要注意的是,上面显示的“setlocal”命令将覆盖ERRORLEVEL。确保在设置errorlevel的命令之前调用setlocal(上面的批处理文件可以处理这个问题)。我不知道它是什么时候被添加的。我知道它在XP和2003服务器中可用,因为我已经用它编写了在这些平台上运行的脚本。不确定它在哪个早期版本的windows上工作。