考虑下面的bat,test.bat(PC01关闭):
mkdir \\PC01\\c$\Test || goto :eof
如果我从命令shell运行该bat:
> test.bat || echo 99
> if ERRORLEVEL 1 echo 55
输出只有55.否99.有一个错误级别,但||
运算符没有看到它。
如果我使用cmd /c -
> cmd /c test.bat || echo 99
> if ERRORLEVEL 1 echo 55
输出为空白。 Errorlevel为0。
如果我删除了|| goto :eof
,那么一切都可以预测 - 即输出将是
99 55
有谁知道为什么这种半生半熟的ERRORLEVEL行为正在发生?
答案 0 :(得分:3)
要使用goto :eof
构建批处理文件的解决方案以设置返回代码,您可以稍微更改一下脚本。
mkdir \\\failure || goto :EXIT
echo Only on Success
exit /b
:exit
(call)
现在你可以使用
test.bat || echo Failed
这里唯一的缺点是失去了错误级别
在这种情况下,返回代码设置为false
,但错误级别始终设置为1
,无效(call)
目前我找不到任何可能的方法来将错误级别和返回代码都设置为用户定义的值
答案 1 :(得分:1)
真正的Errorlevel不会在双管(失败时)运算符中存活。
改用逻辑。例如,下面是您可以这样做的一种方式:
mkdir \\PC01\c$\Test
if "%errorlevel%" == "0" (
echo success
) else (
echo failure
)
<强> 编辑: 强>
如果此前的命令不是单个命令,则必须执行更多操作来跟踪errorlevel。例如,如果您调用脚本,那么在该脚本中您必须管理将errorlevel传递回此代码。
编辑2:
以下是ERRORLEVEL应为&#39; 9009&#39;的测试场景。和他们的输出。
1)没有故障管道,如果是逻辑则使用。
setlocal enableDelayedExpansion
mybad.exe
if "!errorlevel!" == "0" (
echo success !errorlevel!
) else (
echo Errorlevel is now !errorlevel!
echo Errorlevel is now !errorlevel!
)
&#39; mybad.exe&#39;不被视为内部或外部命令, 可操作程序或批处理文件。
Errorlevel现在是9009
Errorlevel现在是9009
2)管道故障,回声
setlocal enableDelayedExpansion
mybad.exe || echo Errorlevel is now !errorlevel!
echo Errorlevel is now !errorlevel!
&#39; mybad.exe&#39;不被视为内部或外部命令, 可操作程序或批处理文件。
Errorlevel现在是1
Errorlevel现在是1
3)管道故障,转到
setlocal enableDelayedExpansion
mybad.exe || goto :fail
exit
:fail
echo Errorlevel is now !errorlevel!
&#39; mybad.exe&#39;不被视为内部或外部命令, 可操作程序或批处理文件。
Errorlevel现在是1
所以,如果你关心的只是&#34; Something&#34;失败了,那好吧。代码1和其他任何东西一样好。但如果你需要知道&#34;什么&#34;失败了,那么你就不能管道失败并让它消灭实际结果。