- 1 year ago
How to use PowerShell to run some code upon system shutdown?
In PowerShell, you can use the Register-WmiEvent cmdlet to register an event that triggers upon system shutdown. Here's an example of how you can use it:
powershell$eventQuery = @"
SELECT * FROM Win32_ComputerShutdownEvent
"@
$action = {
# Code to execute upon system shutdown
# Replace with your own code
Write-Host "System is shutting down..."
}
Register-WmiEvent -Query $eventQuery -Action $action -SourceIdentifier "SystemShutdownEvent"
# Wait for the event to trigger
Wait-Event -SourceIdentifier "SystemShutdownEvent" | Remove-Event
In the example above, the $eventQuery
variable contains a WMI (Windows Management Instrumentation) query that selects the Win32_ComputerShutdownEvent
class. This class represents a system shutdown event.
The $action
variable holds the code you want to execute upon system shutdown. In this example, it simply displays a message using Write-Host
, but you can replace it with your own custom code.
The Register-WmiEvent
cmdlet is used to register the event. It takes the event query, action, and a source identifier as parameters. The source identifier is a unique name for the event registration.
After registering the event, you can use Wait-Event
to wait for the event to trigger. Once the event is triggered (i.e., the system is shutting down), the action specified in $action
will execute. In this example, it will display the "System is shutting down..." message.
Finally, Wait-Event
is piped to Remove-Event
to clean up the event registration.
Save the script with a .ps1
extension (e.g., shutdown_script.ps1
), and you can run it from a PowerShell session. The script will register the event and execute the specified code upon system shutdown.