6

我正在尝试通过 .cmd 文件自动化我使用测试套件制作的程序。

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

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

例如:

1 - 表示因某某原因失败

2 - 表示因其他原因失败

...

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

相反,我想以某种方式说:

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

.bat 文件可以做到这一点吗?还是我必须转向像 python/perl 这样的脚本语言?

4

6 回答 6

14

您可以使用该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 SETLOCALHELP SET以获取有关延迟扩展的更多信息。

于 2008-09-24T22:29:37.190 回答
2

您可以执行类似以下代码的操作。请注意,由于 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
于 2008-09-24T22:23:46.470 回答
1

不完全一样,使用子例程,但您可以使用goto解决方法用文本填充 a 变量。

如果您的这个测试套件增长了很多以使用更强大的语言,它可能会更容易。Perl 甚至 Windows Scripting Host 都可以为您提供帮助。

于 2008-09-24T22:17:21.337 回答
1

是的,您可以使用通话。只是在新行上调用,并传递错误代码。这应该可以,但我没有测试过。

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

于 2008-09-24T22:17:36.920 回答
1

以相反的顺序测试您的值并使用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

如果你想更强大,你可以尝试这样的事情(你需要用 %errorlevel 替换 %1 但对我来说更难测试)。您需要为您处理的每个错误级别添加一个标签:

@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
于 2008-09-24T22:19:38.163 回答
0

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

看:

http://www.robvanderwoude.com/errorlevel.html

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

于 2008-09-24T22:20:44.807 回答