How to ask for batch file user input with a timeout

Matt P picture Matt P · Sep 8, 2012 · Viewed 25k times · Source

So I am trying to add a timer to one of my if statements under a set command but I'm not sure what the command would be. The script will launch and wait thirty minutes before it reboots the PC or wait for a users input to input it at that time or cancel it. So I have my two if statements for the "restart now" and "cancel" set but now I need an if statement to have it count down from thirty minutes before it executes my restart command. Also if anyone knows how to add a visual timer on there showing how much time is left that would be a plus. Thanks guys!!!

@Echo off

:START

set /p answer=PC WILL RESTART IN 30 MINUTES, PRESS N TO RESTART NOW OR C TO CANCEL

if "%answer%"=="n" (GOTO Label1)
if "%answer%"=="c" (GOTO Label2)
if "TIMER GOES HERE" "==" (GOTO Label1)

:Label1

shutdown -r -t 60 -f

:Label2 

exit

Answer

James K picture James K · Sep 8, 2012

I reccomend using CHOICE.EXE, it comes standard with most versions of Windows (with the exception of Windows NT, 2000 and XP, it used to be downloadable from Microsoft's website, but they seem to have overlooked this* one on their ftp site.) and is simple to use.

@Echo off
:START
set waitMins=30

echo PC WILL RESTART IN %waitMins% MINUTES: Press N to restart [N]ow or C to [C]ancel
:: Calculate Seconds
set /a waitMins=waitMins*60
:: Choices are n and c, default choice is n, timeout = 1800 seconds
choice /c nc /d n /t %waitMins%

:: [N]ow = 1; [C]ancel = 2
goto Label%errorlevel%

:Label1

shutdown -r -t 60 -f
:: Make sure that the process doesn't fall through to Lable2
goto :eof

:Label2 
exit

Simply CHOICE.EXE works like this...

choice

...and is the same as...

choice /c yn

...both will display...

[Y,N]?

...and both will wait for the user to press a Y or N.

Choice stores the result in %errorlevel%. Y=1, N=2.

The code I provided takes advantage of the default /D <choice> and timeout /T <seconds> options.

In example...

choice /c yn /d y /t 5

...gives the user a choice of Y or N, will wait for 5 seconds then automaticlly select the default choice of Y, resulting in %ERRORLEVEL%==1.

Another example is...

choice /c abcdef /m "Make a choice. "

...and it displays...

Make a choice. [A,B,C,D,E,F]? 

...and...

A = %ERRORLEVEL% = 1
B = %ERRORLEVEL% = 2
C = %ERRORLEVEL% = 3
D = %ERRORLEVEL% = 4
E = %ERRORLEVEL% = 5
F = %ERRORLEVEL% = 6

There is no ERRORLEVEL 0.

For more on the use of choice, type CHOICE /? at the command prompt.


*NOTE The version of CHOICE.EXE I provided a link to uses slightly different commands, but provides the same functionality.