The simplest way is to use the built-in choice.exe
utility, the Start
command, and obviously, the Exit
command. (windows-vista+)
@%SystemRoot%\System32\choice.exe /M "Are you sure to run this file"
@If ErrorLevel 2 Start %SystemRoot%\System32\notepad.exe "%~f0" & Exit
@Echo Off
.
. rest of the code
.
[EDIT /]
Here's an alternative method, as mentioned in my comment below.
@%SystemRoot%\System32\choice.exe /C YN /N /D N /T 5 /M "Are you sure to run this file"
@If ErrorLevel 2 Start %SystemRoot%\System32\notepad.exe "%~f0" & Exit
@Echo Off
.
. rest of the code
.
The reason, I've advised that you use choice.exe
is that the Set /P
command is potentially dangerous. With it the end user could enter anything at all they wish, including deliberately malicious characters or commands. Your code would therefore need to robustly parse that input without running it, in order not to break your script, or worse.
Here's an example of a method of using Set /P
to perform a similar function.
@Set "#="& Set /P "=Are you sure to run this file? If so, press 'y', anything else cancels"<Nul
@For /F Skip^=1^ Delims^=^ EOL^= %%# In ('%SystemRoot%\System32\replace.exe ? . /U /W') Do @If Not Defined # Set "#=%%#"
@(Set #) 2> NUL | %SystemRoot%\System32\findstr.exe /ILX "#=Y" 1> NUL || (
Start %SystemRoot%\System32\notepad.exe "%~f0"& Exit)
@Echo Off
.
. rest of the code
.