Windows – Executing a batch script on Windows 10 shutdown/logoff/reboot

logofflogoutshutdownwindows 10

First off, sorry. This is a re-post of my original question asked on "stackoverflow", but I have tried to get moderators to move it, due to the question being more a general windows behavior issue then an actual coding problem, but unsuccessful.

But to business.

I am trying to run a BAT-script when the computer (running Win10) receives a command to either shutdown, logoff or reboot. As I am sometimes running virtual machines (in VirtualBox), my script is designed to search for all running VM's, pause them, and then check that no VM-interfaces are still active (as this can lead to the pause state to become corrupt, requiring a fresh reboot of the VM). The script is tested and functioning as intended.

My problem is having it run automatically.

I have tried adding the script to GP under User "Config | Windows Settings | Scripts (Logon/Logoff) | Logoff", as found in previous posts. This seemed to start execution of the script, but did not allow it to properly finish before executing the actual shutdown.

I therefore searched on, and ended up changing another GP value of interest. Under "User Configuration | Administrative Templates | System | Scripts", I enabled "Display instructions in logoff scripts as they run". This causes windows to show the command prompt, and wait for it to close, before continuing the shutdown.

But, I am still facing problems. My current problem is that all the above still happens to late in the shutdown process. When pressing the shutdown button in the start menu, I am first presented with an popup informing me that I still have running program (the VM's), with an option to force stop them. Only after this (forcing my VM's to shutdown the not so pretty way), windows actually executes my script (witch were intended to save the VM's in a proper manor).

My question is therefore if there is a way, preferably using GP and/or task scheduler, that I can have windows execute my BAT-script (and wait for it to finish) when a shutdown/logoff/reboot is triggered, but before the "force close" prompt appears?

Best Regards Henrik V. Nielsen

Best Answer

Necessity is the mother of invention. Not sure if this applies in your VM case though, but:

My Windows 10 answer using gpedit.msc and setting up for logoff scripts was to create a separate ping cmd file with "ping -n 5 127.0.0.1" running after the critical one. That allowed my 'critical' logoff script to work just fine.

Related Question