Win7 CMD:For循环独立工作,但不是批量工作

时间:2015-11-20 00:30:25

标签: batch-file

所以这就是问题,当我独立运行时,这段代码工作正常:

for /f "tokens=1,2 delims==" %%G in ('wmic desktopmonitor get screenheight^,screenwidth /value ^| find "="') do (
    if "%%G"=="ScreenHeight" set /a ResJ=%%H
    if "%%G"=="ScreenWidth" set /a ResI=%%H
)
echo Your screen width is %ResI%
echo Your screen height is %ResJ%
pause

但是,当我将其插入到我正在处理的脚本中时,变量仍为空白:

if errorlevel 1 (
    cd base
    if exist %GameConfig% (
        gzdoom -config %GameConfig% -file %LevelA% %LevelB% %AddonA% %AddonB% %Patch% %HudA% %HudB% %HudC% %Music% -iwad %iWAD%
    ) else (
        for /f "tokens=1,2 delims==" %%G in ('wmic desktopmonitor get screenheight^,screenwidth /value ^| find "="') do (
            if "%%G"=="ScreenHeight" set /a ResJ=%%H
            if "%%G"=="ScreenWidth" set /a ResI=%%H
        )
        echo Your screen width is %ResI%
        echo Your screen height is %ResJ%
        pause
        gzdoom -config %GameConfig% -width %ResI% -height %ResJ% -file %LevelA% %LevelB% %AddonA% %AddonB% %Patch% %HudA% %HudB% %HudC% %Music% -iwad %iWAD%
    )
)

1 个答案:

答案 0 :(得分:1)

您可以访问()块中的变量,这意味着即使它们在代码中被进一步向下引用,但在设置值之前会对整个块进行求值。

  • 解决方案1:在循环内移动相关代码并使用循环变量

    此外,您可以通过在一行中列出值并通过regexp [0-9]获取代码来简化代码。

    for /f "tokens=1,2" %%a in ('
        wmic desktopmonitor get screenheight^,screenwidth ^| findstr /r "[0-9]"
    ') do (
        gzdoom -config %GameConfig% -width %%b -height %%a ..............
    )
    
  • 解决方案2:不要使用外()块,请使用goto

    if errorlevel 1 (
        if exist %GameConfig% ( ...... & goto done) else goto launch
    )
    :launch
        for /f "tokens=1,2" %%a in ('
            wmic desktopmonitor get screenheight^,screenwidth ^| findstr /r "[0-9]"
        ') do set /a ResJ=%%a, ResI=%%b
        gzdoom -config %GameConfig% -width %ResI% -height %ResJ% ........
    :done
        exit /b
    
  • 解决方案3:使用延迟扩展:

    setlocal enableDelayedExpansion
    gzdoom -config %GameConfig% -width !ResI! -height !ResJ! ........
    endlocal