Skip to content

How to Schedule an Automatic Shutdown at a Specific Time in Batch Script

Learn how to schedule, cancel, and manage automatic shutdowns in Windows using Batch scripts, including timer-based commands and Task Scheduler for precise time control.

Scheduling an automatic shutdown is a practical automation task for saving energy, performing off-hours maintenance, or enforcing time limits on computer usage. While the shutdown command accepts a timer in seconds, scheduling for a specific clock time (e.g., exactly at 11:00 PM) requires either time calculation or the Windows Task Scheduler. This guide covers both approaches with proper user warnings, cancellation capability, and recurring schedule management.

This guide explains how to schedule, cancel, and manage automatic shutdowns.

The shutdown Command Reference

Switch Purpose Example
/s Shut down shutdown /s
/r Restart shutdown /r
/t xxx Timer in seconds before action shutdown /s /t 3600 (1 hour)
/f Force-close applications (no "Save?" prompts) shutdown /s /f /t 60
/c "msg" Display a custom message to the user shutdown /s /t 300 /c "Maintenance in 5 min"
/a Abort a pending shutdown shutdown /a

Timer conversion reference:

Duration Seconds
1 minute 60
5 minutes 300
15 minutes 900
30 minutes 1800
1 hour 3600
2 hours 7200
4 hours 14400
8 hours 28800

Method 1: Timer-Based Shutdown (Simple)

The simplest approach: shut down after a specified delay with a user-visible warning message.

Implementation

@echo off
setlocal

set "Minutes=%~1"

:: Handle cancel argument
if /i "%Minutes%"=="cancel" (
    echo [ACTION] Cancelling pending shutdown...
    shutdown /a >nul 2>&1
    if not errorlevel 1 (
        echo [OK] Pending shutdown cancelled.
    ) else (
        echo [INFO] No shutdown was currently pending.
    )
    endlocal
    exit /b 0
)
if "%Minutes%"=="" (
    echo Usage: %~nx0 ^<minutes^>
    echo.
    echo Schedules a shutdown after the specified number of minutes.
    echo.
    echo Examples:
    echo   %~nx0 60      Shut down in 1 hour
    echo   %~nx0 30      Shut down in 30 minutes
    echo   %~nx0 0       Shut down immediately (with 60-second warning^)
    echo.
    echo To cancel a pending shutdown: shutdown /a
    endlocal
    exit /b 1
)

:: Calculate seconds
set /a "Seconds=%Minutes% * 60"

:: Minimum 60-second warning for non-zero timers
if %Seconds% equ 0 set "Seconds=60"

echo [ACTION] Scheduling shutdown in %Minutes% minute(s) (%Seconds% seconds^)...

shutdown /s /t %Seconds% /c "This computer will shut down in %Minutes% minute(s). Save your work and close applications."

if errorlevel 1 (
    echo [ERROR] Failed to schedule shutdown. >&2
    echo A shutdown may already be pending. Cancel it first: shutdown /a >&2
    endlocal
    exit /b 1
)

echo [OK] Shutdown scheduled. The user will see a notification.
echo.
echo [INFO] To cancel: shutdown /a
echo [INFO] Or run: %~nx0 cancel

endlocal
exit /b 0

Method 2: Shutdown at a Specific Clock Time (Task Scheduler)

For scheduling a shutdown at a specific time (e.g., 11:00 PM tonight), the Task Scheduler is the professional approach. It persists across reboots, handles the computer waking from sleep, and doesn't require a Batch window to remain open.

One-Time Shutdown

@echo off
setlocal

set "ShutdownTime=%~1"
set "TaskName=ScheduledShutdown_%RANDOM%"

if "%ShutdownTime%"=="" (
    echo Usage: %~nx0 ^<time^> [/recurring]
    echo.
    echo Schedules a shutdown at the specified time using Task Scheduler.
    echo Time must be in HH:MM format (24-hour^).
    echo.
    echo Examples:
    echo   %~nx0 23:00           Shut down tonight at 11:00 PM
    echo   %~nx0 06:30           Shut down at 6:30 AM
    echo   %~nx0 23:00 /recurring  Shut down every night at 11:00 PM
    endlocal
    exit /b 1
)

:: Check for admin rights
net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Creating scheduled tasks requires administrator privileges. >&2
    endlocal
    exit /b 1
)

:: Check for /recurring flag
set "Schedule=once"
set "TaskName=OneTimeShutdown"
for %%a in (%*) do (
    if /i "%%~a"=="/recurring" (
        set "Schedule=daily"
        set "TaskName=NightlyShutdown"
    )
)

echo [ACTION] Scheduling shutdown for %ShutdownTime% (%Schedule%^)...

:: Create the scheduled task
:: /ru System runs under SYSTEM account (no login required)
:: /rl highest ensures elevated privileges
schtasks /create /tn "%TaskName%" /tr "shutdown.exe /s /t 120 /c \"Scheduled shutdown in 2 minutes. Save your work.\"" /sc %Schedule% /st %ShutdownTime% /ru System /rl highest /f

if errorlevel 1 (
    echo [ERROR] Failed to create scheduled task. >&2
    echo Verify the time format is HH:MM (24-hour^). >&2
    endlocal
    exit /b 1
)

echo [OK] Shutdown scheduled for %ShutdownTime% (%Schedule%^).
echo.

if "%Schedule%"=="once" (
    echo [INFO] The task will run once and remain in Task Scheduler afterward.
    echo        To remove: schtasks /delete /tn "%TaskName%" /f
) else (
    echo [INFO] The shutdown will occur every day at %ShutdownTime%.
    echo        To remove: schtasks /delete /tn "%TaskName%" /f
)

echo.
echo [INFO] Task name: %TaskName%

endlocal
exit /b 0

Why the 120-second timer (/t 120) in the task:

The scheduled task runs shutdown.exe /s /t 120, giving users a 2-minute warning before the shutdown occurs. This warning period allows users who are still working to save their files and close applications. Without it, the shutdown would be immediate and potentially cause data loss.

Why Task Scheduler is better than the wait-loop approach:

Feature Wait-Loop (Batch stays open) Task Scheduler
Requires open CMD window Yes, closing it cancels No, runs in background
Survives reboot No Yes
Works when PC is sleeping No Yes (if configured)
User visibility Hidden (unless minimized) Listed in Task Scheduler
CPU usage while waiting Minimal but non-zero Zero (kernel-managed timer)
Professional/production use No Yes

Method 3: Cancel a Pending Shutdown

Essential companion to any shutdown script: the ability to cancel quickly.

@echo off
setlocal

echo [ACTION] Attempting to cancel pending shutdown...

shutdown /a >nul 2>&1

if not errorlevel 1 (
    echo [OK] Pending shutdown has been cancelled.
) else (
    echo [INFO] No shutdown was currently pending.
)

:: Also check for scheduled tasks
echo.
echo [INFO] Checking for scheduled shutdown tasks...

schtasks /query /tn "OneTimeShutdown" >nul 2>&1
if not errorlevel 1 (
    echo [FOUND] Task "OneTimeShutdown" exists.
    set /p "RemoveTask=Remove this task? (YES/no): "
    if /i "!RemoveTask!"=="YES" (
        schtasks /delete /tn "OneTimeShutdown" /f >nul 2>&1
        echo [OK] Task removed.
    )
)

schtasks /query /tn "NightlyShutdown" >nul 2>&1
if not errorlevel 1 (
    echo [FOUND] Task "NightlyShutdown" exists (recurring^).
    set /p "RemoveRecurring=Remove this recurring task? (YES/no): "
    if /i "!RemoveRecurring!"=="YES" (
        schtasks /delete /tn "NightlyShutdown" /f >nul 2>&1
        echo [OK] Recurring task removed.
    )
)

echo.
echo [DONE] All shutdown operations checked.

endlocal
exit /b 0

Method 4: Scheduled Restart (for Maintenance Windows)

For servers that need to restart (not shut down) during maintenance windows: applying updates, clearing memory leaks, or resetting services.

@echo off
setlocal

set "RestartTime=%~1"

if "%RestartTime%"=="" (
    echo Usage: %~nx0 ^<time^> [/weekly]
    echo.
    echo Schedules a server restart at the specified time.
    echo.
    echo Examples:
    echo   %~nx0 03:00           Restart tonight at 3:00 AM
    echo   %~nx0 02:00 /weekly   Restart every Sunday at 2:00 AM
    endlocal
    exit /b 1
)

net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Administrator privileges required. >&2
    endlocal
    exit /b 1
)

:: Determine schedule type
set "Schedule=once"
set "DaySpec="
set "TaskName=MaintenanceRestart"
for %%a in (%*) do (
    if /i "%%~a"=="/weekly" (
        set "Schedule=weekly"
        set "DaySpec=/d SUN"
        set "TaskName=WeeklyMaintenanceRestart"
    )
)

echo [ACTION] Scheduling maintenance restart for %RestartTime% (%Schedule%^)...

:: /r = restart instead of shutdown
:: /t 300 = 5-minute warning for any overnight users
schtasks /create /tn "%TaskName%" /tr "shutdown.exe /r /t 300 /c \"Scheduled maintenance restart in 5 minutes.\"" /sc %Schedule% %DaySpec% /st %RestartTime% /ru System /rl highest /f

if errorlevel 1 (
    echo [ERROR] Failed to schedule restart task. >&2
    endlocal
    exit /b 1
)

echo [OK] Restart scheduled: %RestartTime% (%Schedule%^)
echo [INFO] Users will receive a 5-minute warning before restart.
echo [INFO] Task name: %TaskName%
echo [INFO] To cancel: schtasks /delete /tn "%TaskName%" /f

endlocal
exit /b 0

Shutdown vs. Restart for maintenance:

Scenario Use Why
Server needs Windows Updates applied /r (restart) Updates finalize during restart; shutdown + manual power-on adds delay
Overnight energy saving /s (shutdown) Server doesn't need to be running; saves power
Memory leak remediation /r (restart) Server needs to come back up immediately
End-of-day workstation policy /s (shutdown) Workstations should be off overnight

View all existing shutdown or restart tasks to manage the scheduled operations.

@echo off
setlocal

echo [INFO] Scheduled shutdown/restart tasks:
echo --------------------------------------------------
echo.

schtasks /query /fo list /v 2>nul | findstr /i /c:"Task Name" /c:"Status" /c:"Next Run" /c:"shutdown" | findstr /i "shutdown Task.Name Status Next"

echo.

:: More detailed check for our specific tasks
for %%t in (OneTimeShutdown NightlyShutdown MaintenanceRestart WeeklyMaintenanceRestart) do (
    schtasks /query /tn "%%t" >nul 2>&1
    if not errorlevel 1 (
        echo [ACTIVE] Task: %%t
        for /f "tokens=1-2 delims=:" %%a in ('schtasks /query /tn "%%t" /fo list ^| findstr /i "Next.Run Status"') do (
            echo          %%a: %%b
        )
        echo.
    )
)

echo --------------------------------------------------

endlocal
exit /b 0

How to Avoid Common Errors

Wrong Way: Immediate Shutdown Without Warning

:: CAUSES DATA LOSS: no time to save open files
shutdown /s /f /t 0

An immediate forced shutdown destroys any unsaved work. Users get no warning.

Correct Way: Always provide a timer AND a message:

shutdown /s /t 300 /c "The system will shut down in 5 minutes. Please save your work."

Wrong Way: Using the Wait-Loop for Production

The pure-Batch wait loop (checking the time every 30 seconds) requires an open CMD window. If the window is closed, the user logs off, or the system restarts, the shutdown is cancelled.

Correct Way: Use Task Scheduler (Method 2) for any production or unattended shutdown. It runs independently of user sessions.

Problem: Shutdown Task Doesn't Run at the Scheduled Time

If the computer is sleeping or hibernating, scheduled tasks don't trigger by default.

Solution: Enable "Wake the computer to run this task" in the task's Conditions tab (see the :::info in Method 2).

Problem: Multiple Pending Shutdowns

Running the timer-based shutdown (Method 1) twice creates a conflict, the second shutdown /s /t fails because a shutdown is already pending.

Solution: Cancel the existing shutdown first:

shutdown /a >nul 2>&1
shutdown /s /t %Seconds% /c "message"

Problem: Shutdown Task Persists After One-Time Use

schtasks /create /sc once creates a task that runs once but remains in Task Scheduler afterward (in a "Ready" state). It won't run again, but it clutters the scheduler.

Solution: Add cleanup to the task command itself, or remove it manually:

schtasks /delete /tn "OneTimeShutdown" /f

Best Practices and Rules

1. Always Provide a Warning Message

Use /c "message" with at least 60 seconds (/t 60) so users can save their work. Immediate silent shutdowns cause data loss.

2. Use Task Scheduler for Production

Timer-based shutdowns and wait-loops are appropriate for quick one-off operations. For recurring, persistent, or unattended shutdowns, always use schtasks.

3. Provide a Cancel Mechanism

Every shutdown script should have a corresponding cancel script (Method 3). Distribute both together.

4. Use /r (Restart) for Maintenance, /s (Shutdown) for Energy Saving

Maintenance restarts should use /r so the server comes back up automatically. Energy-saving shutdowns should use /s to keep the system off.

5. Test with a Long Timer First

When developing shutdown scripts, use /t 3600 (1 hour) so you have time to cancel with shutdown /a if the script behaves unexpectedly. Never test with /t 0 or /f on a production machine.

6. Log Shutdown Events

Scheduled shutdowns should be logged for accountability:

echo [%date% %time%] Shutdown scheduled for %ShutdownTime% by %USERNAME% >> shutdown_schedule.log

Conclusion

Scheduling automatic shutdowns via Batch script ranges from simple timer-based commands to professional Task Scheduler integration. For production environments, schtasks is always the correct choice, it persists across reboots, runs without an open window, and can wake sleeping computers. By providing user-visible warnings, cancellation capability, and proper scheduling parameters, you create a shutdown management system that is reliable, user-friendly, and safe for automated deployment.

Navigation