Windows BAT文件:奇怪的集合(?)行为
我有以下批处理文件代码:Windows BAT文件:奇怪的集合(?)行为,windows,batch-file,cmd,environment-variables,Windows,Batch File,Cmd,Environment Variables,我有以下批处理文件代码: @echo off SET INSTALL_PATH=c:\program files\ :ask_again if exist "%INSTALL_PATH%" ( SET /P PATH_EXISTS_ANSWER=Path exists, overwrite?[y/n/default:n] if not defined PATH_EXISTS_ANSWER ( echo You chose default action^(N^). Try another
@echo off
SET INSTALL_PATH=c:\program files\
:ask_again
if exist "%INSTALL_PATH%" (
SET /P PATH_EXISTS_ANSWER=Path exists, overwrite?[y/n/default:n]
if not defined PATH_EXISTS_ANSWER (
echo You chose default action^(N^). Try another installation path.
echo.
goto default
)
if /I "%PATH_EXISTS_ANSWER%"=="n" (
echo You chose not to use existing folder. Try another installation path.
echo.
goto noc
)
if /I "%PATH_EXISTS_ANSWER%"=="y" (
echo You chose to overwrite existing folder. Existing files will be overwritten.
echo.
goto yesc
)
echo Please choose Y or N
echo.
goto ask_again
)
:yesc
echo you said yes
goto end
:default
echo you said default
goto end
:noc
echo you said no
goto end
:end
当我选择默认动作时,只要按Enter键就可以了。但当我使用N或Y键时,路径的值_EXISTS_ANSWER似乎是未定义的,脚本进入另一个循环,然后,不管我回答什么,脚本somewhy使用前面的答案。
例如,如果我回答Y脚本再次询问,如果我选择N,则键入“Yousaid yes”。
我做错了什么?变量已设置,因此在第一次执行后定义;运行该文件,然后在控制台中键入
echo%PATH\u EXISTS\u ANSWER%
,您将看到上次输入的内容
要防止这种情况,请在开始时将
路径\u EXISTS\u ANSWER
设置为空([]
),或者更好地添加。您需要在@echo off
之后添加以下内容:
SETLOCAL EnableDelayedExpansion
然后,当您参考路径\u EXISTS\u ANSWER
,而不是用百分号括起来,(%
)用感叹号括起来。(!
)像这样:!路径\存在\答案代码>
我对它进行了测试,它运行正常。我怀疑,当光标离开IF块时,CMD.exe会计算变量的实际值。但为什么?也许我很笨,但将变量设置为空并没有用。尽管塞特当地人这样做了。谢谢当然,很高兴能帮上忙。另一个快乐的顾客。(顺便说一句,我也接受投票!)