问题描述
我有一个control_script.cmd,它可以按原样工作,但有点难以阅读。基本上,我想在第一个程序返回错误时退出脚本。
set text=converting something...
call %libdir%\1_convert_xlsx.cmd
set rvalue=%errorlevel%
call :check_errorlevel !rvalue! "!text!"
if !rvalue! geq 1 goto :my_error_handler
set text=loading something...
call %libdir%\2_load_something.cmd
set rvalue=%errorlevel%
call :check_errorlevel !rvalue! "!text!"
if !rvalue! geq 1 goto :my_error_handler
:check_errorlevel
set rvalue=%~1
set text=%~2
echo do something with rvalue and text
exit /b 0
:my_error_handler
exit /b 1
如果我可以将if子句移到check_errorlevel部分,那就更好了
call %libdir%\1_convert_xlsx.cmd
call :check_errorlevel %errorlevel% "converting something..."
call %libdir%\2_load_something.cmd
call :check_errorlevel %errorlevel% "loading something..."
:check_errorlevel
set rvalue=%~1
set text=%~2
echo do something with rvalue and text
if !rvalue! geq 1 goto :my_error_handler
exit /b 0
:my_error_handler
exit /b 1
但是在这里,我面临一个问题::my_error_handler没有在:check_errorlevel中定义,并且我看不到任何其他方法可以直接从:check_errorlevel到我的cmd末尾。有吗?
最诚挚的问候,彼得
解决方法
%因此,在@aschipfl提示之后,我将继续下面的代码。我实际上仍然需要测试,但是我在这里感觉很好。
call %libdir%\1_convert_xlsx.cmd
call :check_errorlevel %errorlevel% "converting something..." || goto :my_error_handler
call %libdir%\2_load_something.cmd
call :check_errorlevel %errorlevel% "loading something..." || goto :my_error_handler
goto :all_fine
:check_errorlevel
set rvalue=%~1
set text=%~2
echo do something with rvalue and text
if %rvalue% GEQ 1 ( set my_errorlevel = 1 ) else ( set my_errorlevel = 0 )
REM notice that this errorlevel only transfers the input-errorlevel and is not an errorlevel by itself.
exit /b %my_errorlevel%
:my_error_handler
exit /b 1
:all_fine
exit /b 0
编辑:{}至()感谢stefano
,这是我提到的宏样式的示例
@Echo off & Setlocal EnableExtensions EnableDelayedExpansion
rem // macro definition within delayed expansion environment requires exclaimation marks to be thrice escaped.
rem // outer For %%n loop uses If ()Else construct to capture the trailing string within the output variable at the time of expansion.
Set "CHKErr=For %%n in (1 2)Do If %%n==2 (If Not "^^^!Errorlevel^^^!"=="0" (Echo/Failed [^^^!Errorlevel^^^!] - ^^^!Output^^^!&Endlocal &Goto :EOF)Else (Echo/Success - ^^^!Output^^^!))Else Set Output="
Call :truelabel 2> Nul
%CHKErr%:truelabel
Call :falselabel 2> Nul
%CHKErr%:falselabel
Echo/You'll never see this on fail.
Goto :Eof
:truelabel
Exit /B 0