如何成功多次调用批处理命令?

时间:2011-08-01 11:27:05

标签: batch-file

我有一个调用各种命令的批处理文件,其中一些命令偶尔因网络问题而失败。重新尝试该命令通常会取得成功。

如何自动重试命令,最多可以尝试一定次数?

这是一些旨在进一步解释的伪代码

call:try numTries "command and arguments"
exit

:try
REM execute %2, trying upto %1 times if it fails
%1 = %1 -1
eval %2
if %errorlevel%==0 exit \B
if %1 > 0 goto try
exit \B

4 个答案:

答案 0 :(得分:2)

您正在寻找以下脚本:

CALL :try numTries "command and arguments"
GOTO :EOF


:try
SET /A tries=%1

:loop
IF %tries% LEQ 0 GOTO return

SET /A tries-=1
EVAL %2 && (GOTO return) || (GOTO loop)

:return
EXIT /B

try子程序的逻辑是:

  1. 将尝试次数存储到变量中。

  2. 开始循环。检查tries变量。如果为0或更小,则返回。

  3. 评估命令和参数。

  4. 如果返回的值为'success'(ERRORLEVEL为0),则返回(从try例程),否则转到#2(循环开始)。

    < / LI>

答案 1 :(得分:2)

没有评估和>(几乎是MatsT答案的复制面食)

$paymentrequest

答案 2 :(得分:0)

尝试类似:

SETLOCAL EnableDelayedExpansion
call:try numTries "command and arguments"
exit

:try
    REM execute %2, trying upto %1 times if it fails
    set count = %1
    set command = %2
    :DoWhile
        if %count%==0 goto EndDoWhile
        set count = %count% -1
        eval %command%
        if %errorlevel%==0 goto EndDoWhile
        if %count% > 0 goto DoWhile
    :EndDoWhile
exit \B

EnableDelayedExpansion是一种在执行时而不是在解析时评估变量的方法。没有它,就无法在循环中保持计数更新。否则大多数代码看起来已经在工作。我不建议更新参数变量本身,因为它通常更安全,并且通过将函数复制到其他变量来启动函数更少混淆。

答案 3 :(得分:0)

僵尸出现了。

考虑使用:

START /wait "command and arguments"