CMD忽略第一个输入

CMD忽略第一个输入,cmd,Cmd,以下程序忽略第一个输入,将再次询问,然后才接受输入 @echo off SETLOCAL IF EXIST C:\Windows\notepad.exe ( :confirm SET /P confirm="overwrite? yn " echo entered: %confirm% IF /I "%confirm%"=="y" GOTO overwrite IF /I "%confirm%"=="n" GOTO no GOTO confirm

以下程序忽略第一个输入,将再次询问,然后才接受输入

@echo off
SETLOCAL
IF EXIST C:\Windows\notepad.exe (
    :confirm
    SET /P confirm="overwrite? yn "
    echo entered: %confirm%
    IF /I "%confirm%"=="y" GOTO overwrite
    IF /I "%confirm%"=="n" GOTO no
    GOTO confirm
    :no
    echo You selected no.
    exit 1
    :overwrite
    echo You selected yes.
)
输入y,y将产生输出:

overwrite? yn y
entered:
overwrite? yn y
entered: y
You selected yes.
输入y,n将导致输出:

overwrite? yn y
entered:
overwrite? yn n
entered: n
You selected no.
我用cmd/k input-test.cmd启动程序

删除IF-EXIST将删除该bug。

您需要。 不要在代码块中使用GOTO和标签!goto confirm会破坏您的代码块,因此不再应用延迟扩展,这就是它第二次工作的原因

但只要稍微改变一下逻辑,就根本不需要代码块:

@echo off
SETLOCAL
IF NOT EXIST C:\Windows\notepad.exe GOTO :eof
:confirm
SET /P confirm="overwrite? yn "
echo entered: %confirm%
IF /I "%confirm%"=="y" GOTO overwrite
IF /I "%confirm%"=="n" GOTO no
GOTO confirm
:no
echo You selected no.
exit 1
:overwrite
echo You selected yes.
同样对于这样简单的用户问题,命令比set/p更适合。它自己进行错误处理,因此它将您的代码减少到:

@echo off
SETLOCAL
IF NOT EXIST C:\Windows\notepad.exe exit /b 2
choice /c YN /m overwrite?
IF errorlevel 2 goto no
if errorlevel 1 goto overwrite

:no
echo You selected no.
exit /b 1
:overwrite
echo You selected yes.

不要在代码块中使用goto:Label;它打破了块上下文!choice命令看起来很有趣,但我无法找到它在哪些平台上可用。我有兴趣在Windows XP和Windows CE 5和7上运行我的脚本,它使用PocketCMD.look查找可用性。注意:XP和VISTA之间的语法略有变化