我最近发现了一个简单的方法,使用set命令提供的/ p选项在windows cmd.exebatch file中获取用户input。 但是出于奇怪的原因,我不明白set / p在if语句之间使用时的performance很棘手。
首先,创build一个名为“ScriptRunsOK.bat”的batch file,代码如下:
@echo off rem Gets a User Yes-No Choice set /p UserInput=Your Choice [Y/N]: set UserChoice=%UserInput:~0,1% if "%UserChoice%"=="y" set UserChoice=Y if "%UserChoice%"=="Y" ( echo You Accepted[%UserChoice%] typing %UserChoice% ) else ( echo You Rejected[%UserChoice%] typing %UserChoice% ) pause
其次,在一个if语句之间创build一个批量文件“ScriptRunsBAD.bat”,其中包含“用户input和评估”代码,仅用于例如purpouses)。 代码如下:
@echo off rem Gets a User Yes-No Choice. Choice Nested in a IF Statement set DummyVar=OK if "%DummyVar%"=="OK" ( set /p UserInput=Your Chiuce [Y/N]: set UserChoice=%UserInput:~0,1% if "%UserChoice%"=="y" set UserChoice=Y if "%UserChoice%"=="Y" ( echo You Accepted[%UserChoice%] typing %UserChoice% ) else ( echo You Rejected[%UserChoice%] typing %UserChoice% ) ) pause
第三,运行“ScriptRunsOK.bat”只需双击它,或直接从de命令行反复。 每次运行它都可以正常工作。 但是,如果您尝试与“ScriptRunsBAD.bat”相同,则它不起作用,而且,当您从命令行运行它时,奇怪地保留了前一次执行时input的用户input。
什么导致行为的“ScriptRunsBAD.bat”的代码? 在if或multi-line语句中使用set / p命令时,是否还需要额外考虑?
好。 最后,阅读@melpomene和@Wimmel发布的链接的内容(谢谢),我可以解决这个问题。 简而言之(进一步的详细信息请参见发布的链接)cmd脚本evals(缺省情况下)每个行被解析时的变量评估(不是当你是程序员时的习惯行为)。 解决的脚本使用SETLOCAL ENABLEDELAYEDEXPANSION
来启用“延迟扩展”,允许在执行时扩展变量,而不是在使用感叹号引用的解析时间(请参阅!UserInput:~0,1!
!UserChoice!
和!UserChoice!
)。
脚本解决了:
@echo off rem Gets a User Yes-No Choice. Choice Nested in a IF Statement set DummyVar=OK SETLOCAL ENABLEDELAYEDEXPANSION if "%DummyVar%"=="OK" ( set /p UserInput=Your Choice [Y/N]: set UserChoice=!UserInput:~0,1! if "!UserChoice!"=="y" set UserChoice=Y if "!UserChoice!"=="Y" ( echo You Accepted[!UserChoice!] typing !UserInput! ) else ( echo You Rejected[!UserChoice!] typing !UserInput! ) ) ENDLOCAL