title: How to use PowerShell to run some code upon system shutdown?
body: <p>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.</p>
  <p>To do the former, I can use <a href="https://docs.microsoft.com/en-us/powershell/module/psscheduledjob/new-jobtrigger" rel="nofollow noreferrer"><code>New-JobTrigger</code></a> and <a href="https://docs.microsoft.com/en-us/powershell/module/psscheduledjob/register-scheduledjob" rel="nofollow noreferrer"><code>Register-ScheduledJob</code></a> in my initial provisioning script like so:</p>
  <pre><code>$StartupTrigger = New-JobTrigger -AtStartup
  Register-ScheduledJob -Name &quot;Startup Job&quot; -Trigger $StartupTrigger -Credential $DesiredCredentials -ScriptBlock {
      Do-InterestingThings $using:ExternalResource
  }
  </code></pre>
  <p>Doesn't even have to be a separate script file, it can just be a <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_script_blocks" rel="nofollow noreferrer">script block</a>. Any variables from an outer scope will be serialized and used when the job runs. Pretty neat.</p>
  <p>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. <strong>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)?</strong> It doesn't need to be a script block, it can be a separate script file.</p>