Pau*_*ith 3 windows loops for-loop batch-file
我已经看到了解决这个问题部分的其他问题,但我没有看到完成整个问题的解决方案.当然,在命令处理器中没有"while"这样的东西,并且因为goto:line语句突破了所有循环,所以在继续下一个值之前,它不是在特定持续时间内迭代某些值集的选项.
这是我正在寻找的逻辑流程的伪代码; 命令处理器阻止了我到目前为止运行它的尝试.你将如何构建这个(除了抛弃批处理脚本并转到c#或其他东西)?
伪代码:
SET %%durationMinutes=60
FOR %%X IN (10 20 40 80 160 200 0) DO (
:: calculate elapsed minutes...
WHILE %elapsedMinutes < %%durationMinutes DO (
:: unrelated hocus pocus here, uses %%X as a variable
call :foo %%X
// can't use goto to simulate the WHILE loop since it breaks %%X, so...?
)
)
Run Code Online (Sandbox Code Playgroud)
这个问题有两面.首先,goto打破任何嵌套IF/FOR命令的事实,但也许更重要的是,与一个组装goto的非常慢的事实.一种解决方案是使用无限循环模拟一段时间:for /L %%i in () do ...并通过goto子程序中断它.此解决方案的问题是for /L不能goto 在同一cmd.exe上下文中断.因此,解决方案是调用新的cmd.exe来执行While.
要在新cmd.exe中执行的批处理文件可能是相同的调用程序文件,因此我们需要通过同一批处理文件中的特殊参数来控制While的执行.此外,我们可以使用辅助变量来使所有东西更清晰.这里是:
@echo off
setlocal EnableDelayedExpansion
rem While dispatcher
if "%1" equ "While" goto %2
rem Definition of auxiliary variables
set While=for /L %%a in () do if
set Do=(
set EndW=) else exit
set RunWhile=cmd /Q /C "%0" While
echo Example of While
echo/
goto RunMyWhile
rem Write the While code here
:MyWhile
set /A i=0, num=0
set /P "num=Enter number: "
%While% !num! gtr 0 %Do%
set /A i+=1
echo !i!- Number processed: !num!
echo/
set num=0
set /P "num=Enter number: "
%EndW% !i!
rem Execute the While here
:RunMyWhile
%RunWhile% MyWhile
set i=%errorlevel%
echo/
echo While processed %i% elements
Run Code Online (Sandbox Code Playgroud)
如您所见,While可能会通过ERRORLEVEL将数字结果返回给调用者代码.
在您的特定情况下:
SET durationMinutes=60
goto RunMyWhile
:MyWhile
:: calculate elapsed minutes...
%WHILE% !elapsedMinutes! < %durationMinutes% %DO%
:: unrelated hocus pocus here, uses %3 as a variable
call :foo %3
:: calculate elapsed minutes again...
%EndW%
:RunMyWhile
FOR %%X IN (10 20 40 80 160 200 0) DO (
%RunWhile% MyWhile %%X
)
Run Code Online (Sandbox Code Playgroud)
这个话题在与详细解释这个职位