【发布时间】:2015-08-25 21:54:27
【问题描述】:
SETLOCAL ENABLEDELAYEDEXPANSION
set list=A B C D E
FOR %%a IN (%list%) DO (
start %%a.exe > ouput_%%a.txt
echo 120, 30 second loops = 60 min
FOR /L %%i IN (1,1,120) DO (
REM pause for 30 seconds
ping 1.1.1.1 -n 1 -w 30000 > nul
echo find the running executable
tasklist | findstr %%a.exe > nul
REM !ERRORLEVEL!
REM exit the script if no executable is found (i.e it has run successfully)
if !ERRORLEVEL! equ 1 goto success
)
REM kill executable if we haven't exited yet
taskkill /f /im %%a.exe
:success
)
这段代码没有像我期望的那样通过 for 循环。我试图做这样的事情 How to break inner loop in nested loop batch script ,但无济于事。有什么建议吗?
编辑
当可执行文件完成运行时,ERRORLEVEL 不为 1。
SETLOCAL ENABLEDELAYEDEXPANSION
set list=A B C D E
FOR %%a IN (%LIST%) DO (
start %%a.exe > ouput_%%a.txt
REM 120, 30 second loops = 60 min
call :innerloop %%a
REM kill executable if we haven't exited yet
taskkill /f /im %%a.exe
)
goto :eof
:innerloop
FOR /L %%i IN (1,1,120) DO (
REM pause for 30 seconds
ping 1.1.1.1 -n 1 -w 30000 > nul
REM find the running executable
tasklist | findstr %%a.exe > nul
REM !ERRORLEVEL!
REM exit the script if no executable is found (i.e it has run successfully)
if %ERRORLEVEL% equ 1 goto :next
)
:next
goto :eof
【问题讨论】:
-
在您编辑的代码中,您需要使用
!ERRORLEVEL!而不是%ERRORLEVEL%!此外,您根本没有查询!ERRORLEVEL! in the outerfor` 循环。您可以测试call :innerloop %%a || taskkill /f /im %%a.exe是否有效(意味着taskkill仅在call返回非零ERRORLEVEL时执行)。
标签: batch-file for-loop nested