.cmd和.bat文件将返回代码转换为错误消息
我正在尝试通过.cmd文件自动化由测试套件制作的程序。
我可以通过%errorlevel%获得运行返回代码的程序。
我的程序为每种类型的错误提供了某些返回码。
例如:
1表示由于某种原因而失败
2表示由于其他原因失败
...
回显失败:测试用例失败,错误级别:%errorlevel%>> TestSuite1Log.txt
相反,我想以某种方式说:
回显失败:测试用例失败,错误原因:lookupError(%errorlevel%)>> TestSuite1Log.txt
.bat文件有可能吗?还是我必须改用python / perl这样的脚本语言?
解决方案
不完全一样,可以使用子例程,但是我们可以使用goto解决方法用文本填充变量。
如果测试套件变得相当强大,可以使用更强大的语言,则可能会更容易。 Perl甚至Windows Scripting Host都可以为我们提供帮助。
是的,我们可以使用通话。只需在新行上进行调用,然后输入错误代码即可。这应该工作,但我还没有测试。
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.
编辑:orry我可能误会了一点,但是我们也可以使用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'语句根据返回码执行不同的操作。
看:
http://www.robvanderwoude.com/errorlevel.html
在回答第二个问题时,我将继续使用脚本语言,因为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",以获取有关延迟扩展的更多信息。