使用goto时,在批处理文件中断开for循环

时间:2016-07-01 08:09:56

标签: batch-file

我需要为文件中的每一行运行一个程序。我一次触发四个实例。在四个实例之后,等待一段时间并触发另一个实例。等待时间后,批处理脚本正在崩溃。

如果我做错了,请建议。

for /F "tokens=*" %%J in ( %JobListFile% ) do (
    SET JobName=%%J
    echo job name !JobName!

    if "!JobName!" equ "" (
        echo joblist not found... rerun the script..
        REM exit /b
    ) else (
        :waittofinish
        for /F "tokens=*" %%a in ( 'tasklist /fi "IMAGENAME eq dsexport.exe" ^| grep -c "dsexport.exe"' ) do ( SET /A CurrInstances=%%a )
        echo current instance is !CurrInstances!
        echo parallelism set to !NoOfParallelInstances!
        if "!CurrInstances!" gtr "!NoOfParallelInstances!" (
            echo going to wait
            sleep 5
            goto waittofinish
            echo failed to go wait label...
        ) else (
            echo Exporting job:   !JobName! ...............Starting
            start /b cmd /C "C:/IBM/9.1/InformationServer/Clients/Classic/dsexport.exe /D=%vDomain% /U=%vuserID% /P=%vpassword% /H=%vServer% %vDSProject% /NODEPENDENTS /JOB=!JobName! %tmppath%\!JobName!.dsx"
            echo.
            echo.
        )
    )

)

echo script completed...

exit /b

1 个答案:

答案 0 :(得分:1)

goto :Label打破括号( ... )中代码块的块上下文;对于for ... do ( ... )循环和if ... ( ... ) else ( ... )条件也是如此。

为了解决这个问题,您可以将带有goto:Label的代码部分放入子例程中,因为这会将来自goto的调用代码部分的块上下文隐藏起来,如下所示:

for /F "usebackq tokens=*" %%J in ( "%JobListFile%" ) do (
    SET "JobName=%%J"
    echo job name !JobName!

    if "!JobName!" equ "" (
        echo joblist not found... rerun the script..
        REM exit /b
    ) else (
        rem /* The `goto` and `:Label` code fragment has been transferred to a subroutine,
        rem    which receives the current value of variable `JobName` as an argument: */
        call :waittofinish "!JobName!"
    )

)

echo script completed...

exit /b


:waittofinish  JobName
rem // This subroutine contains the `goto` and `:Label` code fragment so that it does no longer appear inside of a block `( ... )`:
for /F "tokens=*" %%a in ( 'tasklist /fi "IMAGENAME eq dsexport.exe" ^| grep -c "dsexport.exe"' ) do ( SET /A CurrInstances=%%a )
echo current instance is !CurrInstances!
echo parallelism set to !NoOfParallelInstances!
if "!CurrInstances!" gtr "!NoOfParallelInstances!" (
    echo going to wait
    sleep 5
    goto :waittofinish
    echo failed to go wait label...
) else (
    echo Exporting job:   %~1 ...............Starting
    rem // Not sure if some arguments should be enclosed in `""` in the next line (but I do not know `dsexport.exe`):
    start "" /b cmd /C "C:/IBM/9.1/InformationServer/Clients/Classic/dsexport.exe /D=%vDomain% /U=%vuserID% /P=%vpassword% /H=%vServer% %vDSProject% /NODEPENDENTS /JOB=%~1 %tmppath%\%~1.dsx"
    echo.
    echo.
)
exit /b
<磷>氮。 B。:我没有检查脚本的逻辑,因为我没有/ grep.exedsexport.exe

相关问题