批处理文件无法识别IF-ELSE语句中的任何内容

时间:2019-03-28 15:11:15

标签: windows batch-file cmd

我正试图创建一个批处理文件,以极大地简化人们将来的命令提示符,提供基于文本的菜单供人们选择选项并放置所需的参数,而不是记住这个大命令。

我试图通过FOR来放置它,并修复我认为正确的任何格式,但是没有用。

ECHO {{Are you certain you wish to run EarthShell.bat? (y/N)}}
SET /P confirm=""
FOR ..... DO (
    IF "%confirm%"=="y" (
        ECHO [[ STOPPED: EarthShell.bat encountered an EOF error, and needed to quit. ]]
        THEN ECHO [[ Press any key to exit... ]]
        THEN TIMEOUT /T 600
        EXIT )
    IF "%confirm%"=="Y" (
        ECHO [[ STOPPED: EarthShell.bat encountered an EOF error, and needed to quit. ]]
        THEN ECHO [[ Press any key to exit... ]]
        THEN TIMEOUT /T 600
        EXIT )
    IF "%confirm%"=="N" (
        ECHO [[ Press any key to exit... ]]
        THEN TIMEOUT /T 600
        EXIT )
    IF "%confirm%"=="n"  (
        ECHO [[ Press any key to exit... ]]
        THEN TIMEOUT /T 600
        EXIT
    ) ELSE  (
        ECHO {{Invalid response. Assuming 'N' and exiting EarthShell.bat.}}
        EXIT
    )
)

由于我还没有实际放置命令,因此上面的代码退出了,但没有在读取的IF-ELSE语句中提供任何内容。从理论上讲,当我键入“ y”或“ Y”时,说[[ STOPPED: EarthShell.bat encountered an EOF error, and needed to quit. ]],然后提示按键或等待10分钟的超时结束,然后退出。

1 个答案:

答案 0 :(得分:0)

我真的认为您应该使用Choice命令。下面的示例使用它并大大减少了代码:

@Echo Off
Choice /M "Are you certain you wish to run %~nx0"
If ErrorLevel 2 (Echo Press any key to exit...
    Timeout 6
    Exit /B)
Echo STOPPED: %~nx0 encountered an EOF error, and needed to quit.
Echo Press any key to exit...
Timeout 6

如果您仍然希望使用劣等的Set /P命令和选项:

@ECHO OFF
ECHO {{Are you certain you wish to run %~nx0? (Y/N)}}
SET /P "confirm="
IF /I "%confirm%"=="y" (
    ECHO [[ STOPPED: %~nx0 encountered an EOF error, and needed to quit. ]]
    ECHO [[ Press any key to exit... ]]
    TIMEOUT 6
    EXIT /B
) ELSE (
    IF /I "%confirm%"=="n" (
        ECHO [[ Press any key to exit... ]]
        TIMEOUT 6
        EXIT /B
    ) ELSE (
        ECHO {{Invalid response. Assuming 'N' and exiting %~nx0.}}
        TIMEOUT 6
        EXIT
    )
)

您会注意到,出于这些示例的目的,我用了6秒,因为在复制十分钟的Timeout时没有发现任何好处,您当然可以将其保留为{{ 1}}。