在Windows批处理文件中,我使用一个可选参数,允许调用者跳转到批处理文件的中间并从那里继续.
例如:
if [%1] neq [] (
echo Starting from step %1
goto %1
if %errorlevel% neq 0 goto error
)
:step1
:step2
...
goto end
:error
echo Error handler
...
:end
Run Code Online (Sandbox Code Playgroud)
如果提供的参数不是有效标签,则批处理文件会立即退出,并显示错误.系统找不到指定的批处理标签.
有没有办法让我处理这个错误并执行我的错误处理程序块,或者继续执行整个批处理文件,就像没有提供参数一样?
您可以尝试在定位goto目标的批处理中使用findstr:
findstr /r /i /c:"^:%1" %0>nul
if errorlevel 1 goto error
Run Code Online (Sandbox Code Playgroud)
这有点像黑客,但应该工作.
call :label 当 stderr 重定向时,吐出错误不会吐出错误(谢谢,Johannes),并且似乎不会更改错误级别,而是继续处理批处理文件。您可以在标签后设置一个变量来指示执行是否到了这一步。
@echo off
call :foo 2>nul
echo %errorlevel%
:bar
echo bar
Run Code Online (Sandbox Code Playgroud)
产量
C:\>测试.cmd 系统找不到指定的批次标签 - foo 1 酒吧 C:\>