BAT文件的问题:IF / ELSE无法按预期工作

时间:2013-01-03 17:46:34

标签: batch-file

我正在尝试制作一个简短的BAT文件,但我遇到了其中一个功能问题。我已经尝试了许多不同的方法来做到这一点,但它们似乎都没有用,但作为初学者,我无法弄清楚问题。基本上,脚本在运行时应该检查某个.BAT文件是否存在,如果存在,脚本会询问用户是否要运行它。如果用户指示Y,则调用另一个BAT,然后继续执行原始脚本。如果用户指示N,则该脚本应该在不调用其他BAT的情况下继续。到目前为止,脚本始终注意并询问文件,但在提示符下选择Y永远不会起作用。我确信解决方案很明显,但它正在逃避我。这是代码:

SET /P kmname=Enter database name:

:kmstart

IF EXIST C:\Visual\area\%kmname%\%kmname%.flt (
        ECHO %kmname%.flt found, will now create %kmname%.ive.
        CD C:\Visual\area\%kmname%\
        IF EXIST Preprocess.bat (
            SET /P kmpreproc=Found Preprocess.bat. Do you want to run it now?
            IF /I "%kmpreproc%" EQU "Y" (
                GOTO PREPROC
            ) ELSE (
                GOTO CONTINUE
            )
        )
        GOTO CONTINUE   
    ) ELSE (
        ECHO C:\Visual\area\%kmname%\%kmname%.flt does not exist. Try again.
        SET /P kmname=Enter database name: 
        GOTO kmstart
    )
:PREPROC
ECHO Running Preprocess.bat.
:CONTINUE
ECHO Continuing process.
PAUSE

2 个答案:

答案 0 :(得分:2)

问题是你的变量在进入if之前正在被评估,这意味着cmd在结束之前不会看到任何变化。

这会导致您的变量kmpreproc出现问题,并且取决于if结果,kmname块内的if更改。

修复程序(假设其余代码正常运行)是通过将变量%更改为!来启用延迟扩展并使用延迟扩展而非正常扩展。 / p>

setlocal enabledelayedexpansion
SET /P kmname=Enter database name:

:kmstart

IF EXIST C:\Visual\area\!kmname!\!kmname!.flt (
        ECHO !kmname!.flt found, will now create !kmname!.ive.
        CD C:\Visual\area\!kmname!\
        IF EXIST Preprocess.bat (
            SET /P kmpreproc=Found Preprocess.bat. Do you want to run it now?
            IF /I "!kmpreproc!" EQU "Y" (
                GOTO PREPROC
            ) ELSE (
                GOTO CONTINUE
            )
        )
        GOTO CONTINUE   
    ) ELSE (
        ECHO C:\Visual\area\!kmname!\!kmname!.flt does not exist. Try again.
        SET /P kmname=Enter database name: 
        GOTO kmstart
    )
:PREPROC
ECHO Running Preprocess.bat.
:CONTINUE
ECHO Continuing process.
PAUSE

答案 1 :(得分:0)

以下是我更正后的代码:

@echo off
SET /P kmname=Enter database name:

:kmstart

IF EXIST C:\Visual\area\%kmname%\%kmname%.flt (
        ECHO %kmname%.flt found, will now create %kmname%.ive.
        CD C:\Visual\area\%kmname%\
        IF EXIST Preprocess.bat (
            SET /P kmpreproc=Found Preprocess.bat. Do you want to run it now?
            IF /I "%kmpreproc%"=="Y" (
                GOTO PREPROC
                ) 
        GOTO CONTINUE  
        )       
)
        ECHO C:\Visual\area\%kmname%\%kmname%.flt does not exist. Try again.
        SET /P kmname=Enter database name: 
        GOTO kmstart

:PREPROC
ECHO Running Preprocess.bat.
call "cmd /c start Preprocess.bat"
pause

:CONTINUE
ECHO Continuing process.
PAUSE

如果不起作用,请尝试在setlocal EnableDelayedExpansion下撰写@echo off并将所有%替换为!