2

I want to run an executable that saves an XML file on a local drive before the computer (running on Windows 7) gets shut down.

I know it is possible to run scripts before shutdown. This can be configured in Local Group Policy Editor under Computer Configuration --> Windows Settings --> Scripts(Startup/Shutdown).

I have tried to put my executable in the shutdown property, but it does not work. How can I run an executable before the computer gets shut down? How can I hook up the shutdown event?

3
  • Have you tried to see why it didn't work at the system log?
    – Vinícius Gobbo A. de Oliveira
    Jan 21, 2014 at 15:08
  • Also have you tried it using the task scheduler too?
    – RononDex
    Jan 21, 2014 at 15:15
  • I found solution for similar question
    – Utamaru
    Jan 21, 2014 at 15:17

1 Answer 1

7

Launching a process when the shutdown was initiated is a bad idea. At this stage the most likely outcome is to get back the error 1115 ERROR_SHUTDOWN_IN_PROGRESS.

A much better way is to install a service and register the service to receive shutdown notifications via RegisterServiceCtrlHandlerEx, see shutting down:

Service applications receive shutdown notifications in their handler routines. To register a service control handler, use the RegisterServiceCtrlHandlerEx function.

A C# service would do this by setting CanShutdown to true and then handling the OnShutdown event. It is important to be service, not an application, as shutdown can occur when no session is logged on and/or multiple sessions could be running when the shutdown occurs.

1
  • This does not always work. I've set CanShutdown to true, implemented OnShutdown which writes to a simple file. The file is never written to. Service runs as local system so I know it has permissions.
    – jjxtra
    Feb 18, 2018 at 23:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .