0

我需要帮助创建一个 for 循环,该循环根据变量生成以下示例代码%count%,然后执行它:

因此,如果 %count%=4 它将输出以下内容:

IF %M%==1 set %variable%
IF %M%==2 set %variable%
IF %M%==3 set %variable%
IF %M%==4 EXIT

如果 %count%= 7 输出将是:

IF %M%==1 set %variable%
IF %M%==2 set %variable%
IF %M%==3 set %variable%
IF %M%==4 set %variable%
IF %M%==5 set %variable%
IF %M%==6 set %variable%
IF %M%==7 EXIT

我正在考虑将 for 循环回显到一个新的批处理文件中,然后执行它,不确定这是否是最好的方法?

前任:

for /l %%a in (1,1,%count%) do (
echo IF %M%==%count% set %variable% > new.bat
)

call new.bat
4

2 回答 2

3

为什么必须动态生成和执行代码?

您可以使用以下简单的静态代码获得相同的最终结果:

set /a count2=count-1
for /l %%N in (1 1 %count2%) do if %M% equ %%N set %variable%
if %M% equ %count% exit

如果你知道 M 是数字,那么:

if %M% geq 1 if %M% lss %count% set %variable%
if %M% equ %count% exit
于 2013-09-12T17:33:51.640 回答
0

要直接调用它,您可以使用:

cmd /Q /C echo Command1 & echo Command2 & pause或者cmd /Q /C %variable%

不过,您当然会希望以这种方式注意引号。要获得所有选项,请使用cmd /?,但大多数基本选项是:

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]
/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.
于 2013-09-12T16:39:34.600 回答