Search code examples
if-statementbatch-filetimershutdownrestart

How to ask for batch file user input with a timeout


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

Solution

  • Similar one for hibernate.

    @echo off
    setlocal enableDelayedExpansion
    for /l %%N in (600 -1 1) do (
      set /a "min=%%N/60, sec=%%N%%60, n-=1"
      if !sec! lss 10 set sec=0!sec!
      cls
      choice /c:CN1 /n /m "HIBERNATE in !min!:!sec! - Press N to hibernate Now, or C to Cancel. " /t:1 /d:1
      if not errorlevel 3 goto :break
    )
    cls
    echo HIBERNATE in 0:00 - Press N to hibernate Now, or C to Cancel.
    :break
    if errorlevel 2 (%windir%\System32\rundll32.exe powrprof.dll,SetSuspendState Hibernate) else echo Hibernate Canceled