Windows – How to run a batch script at shutdown in Windows 10 home edition

automationbatch filescriptshutdownwindows 10

I need to run batch scripts at shutdown of Windows 10 home edition, both on manual restarts and on automatic restarts due to Windows automatic updates. This needs to work while no users are logged in too.
So far I've tried:

  1. Scheduled Task at eventid 1047 (discarded, won't wait till my script is over).
  2. Manually adding Group Policy shutdown scripts to registry and to C:\WINDOWS\SYSTEM32\GroupPolicy (discarded, won't run since it looks like the functionality is disabled by restraints imposed by the Windows edition.)
  3. Third party software. Weird enough, I couldn't find any free tool that would run as a service and allow me to add .bat files to be run at system (or service) shutdown.
  4. I tried AutoHotkey + NSSM [The Non-Sucking Service Manager] as a custom service, but AutoHotkey's events wouldn't trigger every time.

I'm quite disenchanted with this limitation. ?
Any ideas?

Edit1: Take into account Windows automatic updates.
Edit2: This needs to work while no users are logged in too.
Edit4: I'm waiting for the next Windows automatic restart due to a Windows update to see if running shutdown -a at the beginning of the batch file and then shutdown -s at the end within a scheduled task at shutdown event approach works.
Edit5: Bummer, it didn't work. The scheduled task did not start: Error: "Shutdown in progress". I guess my only hope is a third-party tool.

Best Answer

I've done this with AutoHotkey before. This script is tested and working.

I made a basic batch file that will create a "test file" on the desktop. Just run the AHK file and leave it running. When the script detects a shutdown, it'll run the batch file.

Make sure you set the path to your text file at the top of the script.

AutoHotkey Script:

;==============================
;Set the path to your batch file.
path    := "C:\batch.bat"
;==============================

; Run script as admin. This will allow your batch file to be ran with admin priv.
if not A_IsAdmin
{
   Run *RunAs "%A_ScriptFullPath%"  ; Requires v1.0.92.01+
   ExitApp
}

; Only allow one instance of the script to run.
#SingleInstance, Force

; If you don't want an icon to show in the tray,
; remove the semicolon from the line below.
;#NoTrayIcon

; When script detects WM_QUERYENDSESSION (a shutdown), run OnShutDown function.
OnMessage(0x11, "OnShutDown")
return

OnShutDown(){
    ; Run the batch file.
    Run, % path
    ExitApp
}

Batch file I used for testing:

echo Write file before shutdown > %USERPROFILE%\Desktop\ShutdownTest.txt

If you wanted to, you could always execute your batch file commands directly through AHK.

Related Question