JesseTG
JesseTG

Reputation: 2123

How to use PowerShell to run some code upon system shutdown?

I'm provisioning a Windows VM that needs to run some PowerShell code when it boots. It also needs to run some different code when it shuts down.

To do the former, I can use New-JobTrigger and Register-ScheduledJob in my initial provisioning script like so:

$StartupTrigger = New-JobTrigger -AtStartup
Register-ScheduledJob -Name "Startup Job" -Trigger $StartupTrigger -Credential $DesiredCredentials -ScriptBlock {
    Do-InterestingThings $using:ExternalResource
}

Doesn't even have to be a separate script file, it can just be a script block. Any variables from an outer scope will be serialized and used when the job runs. Pretty neat.

The real problem I'm solving involves creating an external resource whose lifetime is tied to the VM's uptime. When the VM is created, this resource will be created. When the VM is shut down, this resource needs to be cleaned up.

How can I use PowerShell to run some code just before the VM is scheduled to shut down (regardless of how it got the order)?

It doesn't need to be a script block, it can be a separate script file.

Upvotes: 2

Views: 4580

Answers (1)

Cpt.Whale
Cpt.Whale

Reputation: 5341

There are two reasonable ways to do this:

Local Group Policy:

This can be done in the local group policy editor: gpedit.msc. Navigate to Computer Configuration/Windows Settings/Scripts (Startup/Shutdown)/Shutdown. You can add 'Scripts' and/or 'PowerShell Scripts' here which get executed before other shutdown processes.


Event-Based Scheduled Task:

From this answer:

scheduled task as follows:

  • Type : On Event (Basic)
  • Log : System
  • Source : User32
  • EventID : 1074

When a user or command initiates a shutdown or restart as a logged on user or on a user's behalf, event ID 1074 will fire. By creating a task to use this to trigger a script, it will start the script and allow it to finish

Note that this does not delay the shutdown (so has to be quick) and can sometimes fail to trigger before the task scheduler service stops.


Final Note:

Always make sure that your code can handle a dirty shutdown. After all, the fastest way to call a reboot is the power button...

Upvotes: 4

Related Questions