PsShutdown
You could use Mark Rusinovich's psshutdown which does exactly what you want:
- initiates shutdown after specified amount of time
- displays countdown
- allows user to cancel with a cancel button
It is free to use.
Commandline: psshutdown -k -f -t 30 -c
-k
shuts down the computer (ACPI power off)
-f
forces programs to terminate if necessary
-t 30
introduces a delay of 30 seconds before shutdown
-c
allows user to cancel shutdown with Cancel button
( Screenshot from superuser.com )
Choice
Another option would be to call choice /t 1
multiple times:
@echo off
set /a "t=30"
:loop
set /a "t-=1"
if "%t%" == "0" goto timedout
cls
choice /T 1 /C sc /N /D s /M "Shutdown in %t% seconds, press c to cancel: "
if not "%errorlevel%" == "1" goto cancelled
goto loop
:cancelled
echo You cancelled shutdown
pause
goto :eof
:timedout
echo Shutting down
shutdown /s /f /t 1
pause
goto :eof
set /a "t=30"
sets variable t
to 30
set /a "t-=1"
substracts 1 from t
if "%t%" == "0" goto timedout
initiates shutdown when t
reaches zero
cls
clears previous text from screen
choice
is timeout
that knows if it was cancelled but without printing time
/T 1
- timeout in 1 second (to update the message)
/C sc
- choice 1 is s, choice 2 is c
/N
- don't display [s,c]
in the end
/D s
- default option on 1-second-timeout is s
/M "Shutdown in %t% ..."
- display message with current value of variable t
Please note that shutdown /s /f /t NNN
may not behave the same as shutdown /s /f
without time, so I included /t 1
just in case.
Shutdown /a
It may be advantageous to actually initiate shutdown before the countdown, but allow the user to abort it:
Do the countdown as described in previous section ("Choice").
- You could get away with just plain
timeout
command with a few more seconds in hopes that the batch script is aborted by shutdown before the time runs out but it would be very confusing and unreliable, so this is not recommended
Before beginning the countdown (:loop
) start the shutdown like this:
shutdown /s /f /t 30
If timed out, do nothing (remove shutdown /s /f /t 1
after timedout:
)
If user cancelled (right after :cancelled
), abort it with: shutdown /a