I love Bill's approach, but he doesn't tell you how to register for a WMI Event in PowerShell, so here's how to do it.
If you want your code to trigger only when the System Power State changes, as described here, use this code.
Register-WMIEvent -query "Select * From Win32_PowerManagementEvent" `
-sourceIdentifier "Power" `
-action {
#YourCodeHere
}
Now, this will trigger whenever the power state changes, whether you plug the device in, OR unplug it. So you might further want to stop and pause to ask the question:
Am I on power or not?
Fortunately we can do that via the WMI Class BatteryStatus
, so here's the full construct that I use to ONLY run an operation when a power event changes, and then only if I'm no longer on Power.
Register-WMIEvent -query "Select * From Win32_PowerManagementEvent" `
-sourceIdentifier "Power" `
-action {
if ([BOOL](Get-WmiObject -Class BatteryStatus -Namespace root\wmi).PowerOnLine ){
#Device is plugged in now, do this action
write-host "Power on!"
}
else{
#Device is NOT plugged in now, do this action
write-host "Now on battery, locking..."
[NativeMethods]::LockWorkStation()
}