如何在 Windows 批处理文件中发出“你确定”提示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1794547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make an "are you sure" prompt in a Windows batchfile?
提问by Josh Ribakoff
I have a batch file that automates copying a bunch of files from one place to the other and back for me. Only thing is as much as it helps me I keep accidentally selecting that command off my command buffer and mass overwriting uncommited changes.
我有一个批处理文件,可以自动将一堆文件从一个地方复制到另一个地方,然后再返回给我。唯一能帮助我的是我一直不小心从我的命令缓冲区中选择该命令并大量覆盖未提交的更改。
What code would I need for my .bat file to make it say "are you sure", and make me type "y" before it ran the rest of the file? If anything but "y" is typed it should exit execution on that line.
我的 .bat 文件需要什么代码才能让它说“你确定”,并让我在运行文件的其余部分之前输入“y”?如果输入了除“y”之外的任何内容,它应该在该行退出执行。
EditNov 27 Ok I marked this unanswered again because I still can't figure it out. When I call "exit;" it closes cmd.exe which is not what I want. All this because Windows implemented command buffer wrong [differently than what I am used to at least]
编辑11 月 27 日 好的,我再次将此标记为未答复,因为我仍然无法弄清楚。当我叫“退出”时;它关闭了 cmd.exe,这不是我想要的。所有这一切都是因为 Windows 实现的命令缓冲区错误 [至少与我习惯的不同]
回答by Joe
You want something like:
你想要这样的东西:
@echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
echo ... rest of file ...
:END
endlocal
回答by Steven A. Lowe
try the CHOICE command, e.g.
尝试CHOICE 命令,例如
CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
回答by ghostdog74
The choice
command is not available everywhere. With newer Windows versions, the set
command has the /p
option you can get user input
该choice
命令并非随处可用。对于较新的 Windows 版本,该set
命令具有/p
可以获取用户输入的选项
SET /P variable=[promptString]
see set /?
for more info
查看set /?
更多信息
回答by Mofi
There are two commands available for user prompts on windows command line:
有两个命令可用于 Windows 命令行上的用户提示:
- setwith option
/P
available on all Windows NT versions with enabled command extensions and - choice.exeavailable by default on Windows Vista and later Windows versions for PC users and on Windows Server 2003 and later server versions of Windows.
- 设置选项
/P
可用于所有启用命令扩展的 Windows NT 版本和 - 对于 PC 用户,Windows Vista 和更高版本的 Windows 以及 Windows Server 2003 和更高的 Windows 服务器版本上默认提供choice.exe。
setis an internal command of Windows command processor cmd.exe
. The option /P
to prompt a user for a string is available only with enabled command extensions which are enabled by default as otherwise nearly no batch file would work anymore nowadays.
set是 Windows 命令处理器的内部命令cmd.exe
。该选项/P
为一个字符串提示用户是仅与默认情况下启用否则几乎没有批处理文件将继续工作,如今已启用的命令扩展。
choice.exeis a separate console application (external command) located in %SystemRoot%\System32
. choice.exe
of Windows Server 2003 can be copied into directory %SystemRoot%\System32
on a Windows XP machine for usage on Windows XP like many other commands not available by default on Windows XP, but available by default on Windows Server 2003.
choice.exe是一个单独的控制台应用程序(外部命令),位于%SystemRoot%\System32
. choice.exe
Windows Server 2003 的目录可以复制到%SystemRoot%\System32
Windows XP 机器上的目录中,以便在 Windows XP 上使用,就像许多其他命令在 Windows XP 上默认不可用,但在 Windows Server 2003 上默认可用。
It is best practice to favor usage of CHOICEover usage of SET /Pbecause of the following reasons:
由于以下原因,最好使用CHOICE 而不使用SET /P:
- CHOICEaccepts only keys (respectively characters read from STDIN) specified after option
/C
(and Ctrl+C) and outputs an error beep if the user presses a wrong key. - CHOICEdoes not require pressing any other key than one of the acceptable ones. CHOICEexits immediately once an acceptable key is pressed while SET /Prequires that the user finishes input with RETURNor ENTER.
- It is possible with CHOICEto define a default option and a timeout to automatically continue with default option after some seconds without waiting for the user.
- The output is better on answering the prompt automatically from another batch file which calls the batch file with the prompt using something like
echo Y | call PromptExample.bat
on using CHOICE. - The evaluation of the user's choice is much easier with CHOICEbecause of CHOICEexits with a value according to pressed key (character) which is assigned to ERRORLEVELwhich can be easily evaluated next.
- The environment variable used on SET /Pis not defined if the user hits just key RETURNor ENTERand it was not defined before prompting the user. The used environment variable on SET /Pcommand line keeps its current value if defined before and user presses just RETURNor ENTER.
- The user has the freedom to enter anything on being prompted with SET /Pincluding a string which results later in an exit of batch file execution by
cmd
because of a syntax error, or in execution of commands not included at all in the batch file on not good coded batch file. It needs some efforts to get SET /Psecure against by mistake or intentionally wrong user input.
- CHOICE仅接受在选项(和)之后指定的键(分别是从STDIN读取的字符),如果用户按错了键,则输出错误提示音。
/C
Ctrl+C - CHOICE不需要按可接受的键之一以外的任何其他键。一旦按下可接受的键,CHOICE立即退出,而SET /P要求用户用RETURN或完成输入ENTER。
- 这是可能的CHOICE定义默认选项和超时默认选项自动继续在几秒钟后无需等待用户。
- 输出更好地从另一个批处理文件自动回答提示,该批处理文件使用类似于
echo Y | call PromptExample.bat
使用CHOICE的提示调用批处理文件。 - 使用CHOICE对用户的选择进行评估要容易得多,因为CHOICE以根据按下的键(字符)的值退出,该值分配给ERRORLEVEL,接下来可以轻松评估。
- SET /P上使用的环境变量未定义,如果用户只点击键,RETURN或者ENTER在提示用户之前未定义。SET /P命令行上使用的环境变量如果之前定义并且用户只按RETURN或 ,则保持其当前值ENTER。
- 用户可以在SET /P提示时自由输入任何内容,包括一个字符串,该字符串稍后会
cmd
由于语法错误而导致批处理文件执行退出,或者执行批处理文件中根本不包含的命令良好的编码批处理文件。需要一些努力才能使SET /P免受错误或故意错误的用户输入的影响。
Here is a prompt example using preferred CHOICEand alternatively SET /Pon choice.exe
not available on used computer running Windows.
这是一个使用首选CHOICE的提示示例,或者SET /Ponchoice.exe
在运行 Windows 的已用计算机上不可用。
@echo off
echo This is an example for prompting a user.
echo/
if exist "%SystemRoot%\System32\choice.exe" goto UseChoice
setlocal EnableExtensions EnableDelayedExpansion
:UseSetPrompt
set "UserChoice=N"
set /P "UserChoice=Are you sure [Y/N]? "
set "UserChoice=!UserChoice: =!"
if /I "!UserChoice!" == "N" endlocal & goto :EOF
if /I not "!UserChoice!" == "Y" goto UseSetPrompt
endlocal
goto Continue
:UseChoice
%SystemRoot%\System32\choice.exe /C YN /N /M "Are you sure [Y/N]? "
if errorlevel 2 goto :EOF
:Continue
echo So your are sure. Okay, let's go ...
Note:This batch file uses command extensions which are not available on Windows 95/98/ME using command.com
instead of cmd.exe
as command interpreter.
注意:此批处理文件使用在 Windows 95/98/ME 上不可用的命令扩展名,command.com
而不是cmd.exe
用作命令解释器。
The command line set "UserChoice=!UserChoice: =!"
is added to make it possible to call this batch file with echo Y | call PromptExample.bat
on Windows NT4/2000/XP and do not require the usage of echo Y| call PromptExample.bat
. It deletes all spaces from string read from STDINbefore running the two string comparisons.
set "UserChoice=!UserChoice: =!"
添加命令行是为了可以echo Y | call PromptExample.bat
在 Windows NT4/2000/XP 上调用此批处理文件,并且不需要使用echo Y| call PromptExample.bat
. 在运行两个字符串比较之前,它会删除从STDIN读取的字符串中的所有空格。
echo Y | call PromptExample.bat
results in YSPACEgetting assigned to environment variable UserChoice
. That would result on processing the prompt twice because of "Y "
is neither case-insensitive equal "N"
nor "Y"
without deleting first all spaces. So UserChoice
with YSPACEas value would result in running the prompt a second time with option N
as defined as default in the batch file on second prompt execution which next results in an unexpected exit of batch file processing. Yes, secure usage of SET /Pis really tricky, isn't it?
echo Y | call PromptExample.bat
导致YSPACE被分配给环境变量UserChoice
。这将导致对提示进行两次处理,因为"Y "
既不区分大小写,"N"
也不"Y"
首先删除所有空格。因此UserChoice
,将YSPACE作为值将导致第二次运行提示N
,并在第二次提示执行时使用批处理文件中定义为默认值的选项,这将导致批处理文件处理意外退出。是的,安全使用SET /P真的很棘手,不是吗?
For even more details on usage of SET /Pand CHOICEfor prompting user for a choice from a list of options see answer on How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?
有关使用SET /P和CHOICE提示用户从选项列表中进行选择的更多详细信息,请参阅有关如何停止 Windows 命令解释器对不正确的用户输入退出批处理文件执行的回答?
Some more hints:
还有一些提示:
- IFcompares the two strings left and right of the comparison operator with includingthe double quotes. So case-insensitive compared is not the value of
UserChoice
withN
andY
, but the value ofUserChoice
surrounded by"
with"N"
and"Y"
. - The IFcomparison operators
EQU
andNEQ
are designed primary for comparing two integers in range -2147483648 to 2147483647 and not for comparing two strings.EQU
andNEQ
work also for strings comparisons, but result on comparing strings in double quotes on a useless attempt to convert left string to an integer.EQU
andNEQ
can be used only with enabled command extensions. The comparison operators for string comparisons are==
andnot ... ==
which work even with disabled command extensions as evencommand.com
of MS-DOS and Windows 95/98/ME already supported them. For more details on IFcomparison operators see Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files. - The command
goto :EOF
requires enabled command extensions to really exit batch file processing. For more details see Where does GOTO :EOF return to?
- IF比较比较运算符左边和右边的两个字符串,包括双引号。所以不区分大小写的比较不是
UserChoice
withN
andY
的值,而是with andUserChoice
包围的值。"
"N"
"Y"
- 所述IF比较运算符
EQU
和NEQ
被用于在范围-2147483648比较两个整数2147483647,而不是为了比较两个字符串设计初级。EQU
并且NEQ
也适用于字符串比较,但结果是在将左字符串转换为整数的无用尝试中比较双引号中的字符串。EQU
并且NEQ
只能与启用的命令扩展一起使用。用于字符串比较的比较运算符是==
和not ... ==
甚至可以在禁用命令扩展的情况下工作,因为即使command.com
MS-DOS 和 Windows 95/98/ME 已经支持它们。有关IF比较运算符的更多详细信息,请参阅符号等效于 Windows 批处理文件中的 NEQ、LSS、GTR 等。 - 该命令
goto :EOF
需要启用命令扩展才能真正退出批处理文件处理。有关更多详细信息,请参阅GOTO :EOF 返回何处?
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
要了解使用的命令及其工作原理,请打开命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
choice /?
echo /?
endlocal /?
goto /?
if /?
set /?
setlocal /?
See also:
也可以看看:
- This answerfor details about the commands SETLOCALand ENDLOCAL.
- Why is no string output with 'echo %var%' after using 'set var = text' on command line?
It explains the reason for using syntaxset "variable=value"
on assigning a string to an environment variable. - Single line with multiple commands using Windows batch filefor details on
if errorlevel X
behavior and operator&
. - Microsoft documentation for using command redirection operatorsexplaining redirection operator
|
and handle STDIN. - Wikipedia article about Windows Environment Variablesfor an explanation of
SystemRoot
. - DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/
- This answer有关命令SETLOCAL和ENDLOCAL 的详细信息。
- 为什么在命令行上使用“set var = text”后没有带有“echo %var%”的字符串输出?
它解释了使用语法set "variable=value"
将字符串分配给环境变量的原因。 - 使用 Windows 批处理文件的多条命令的单行以获取有关
if errorlevel X
行为和操作员的详细信息&
。 - 使用命令重定向运算符的Microsoft 文档解释了重定向运算符
|
和处理STDIN。 - 维基百科关于Windows 环境变量的文章,用于解释
SystemRoot
. - DosTips 论坛主题ECHO。无法给出文本或空行 - 而是使用 ECHO/
回答by Bob Smith
Here a bit easier:
这里简单一点:
@echo off
set /p var=Are You Sure?[Y/N]:
if %var%== Y goto ...
if not %var%== Y exit
or
或者
@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no
回答by Z. Mickaels
If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".
如果您想让批处理程序退出回到提示而不关闭提示(AKA cmd.exe),您可以使用“exit /b”。
This may help.
这可能会有所帮助。
set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)
Or if you don't want to use as many lines...
或者,如果您不想使用尽可能多的行...
Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.
Hope this helps...
希望这可以帮助...
回答by Z. Mickaels
Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.
这是我在 Windows 10 上的备份(.bat/批处理)脚本中使用的一个简单示例,它允许我在进行备份时有不同的选项。
...
:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice
:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done
:doonotsyncthefiles
echo Backup Complete!
...
You can have as many as you need of these blocks.
您可以拥有任意数量的这些块。
回答by Ste
Here's my go-to method for a yes/noanswer.
这是我回答是/否的首选方法。
It's case-insensitive also.
它也不区分大小写。
This just checks for the errors given by the input and sets the choice
variable to whatever you require so it can be used below in the code.
这只是检查输入给出的错误并将choice
变量设置为您需要的任何值,以便它可以在下面的代码中使用。
@echo off
choice /M "[Opt 1] Do you want to continue [Yes/No]"
if errorlevel 255 (
echo Error
) else if errorlevel 2 (
set "YourChoice=will not"
) else if errorlevel 1 (
set "YourChoice=will"
) else if errorlevel 0 (
goto :EOF
)
echo %YourChoice%
pause
回答by user13636521
First, open the terminal.
首先,打开终端。
Then, type
然后,键入
cd ~
touch .sure
chmod 700 .sure
Next, open .sure and paste this inside.
接下来,打开 .sure 并将其粘贴到里面。
#!/bin/bash --init-file
PS1='> '
alias y='
exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''
After that, close the file.
之后,关闭文件。
~/.sure ; ENTER COMMAND HERE
This will give you a prompt of are you sure before continuing the command.
在继续命令之前,这会给你一个你确定的提示。