Triggering tasks and running programs when Windows 7 is plugged in or unplugged? [duplicate]
By default, Windows does not log an event when you unplug or plug in your computer.
However, with PowerShell you can listen for such a change and write your own events to the log. This script will do that:
New-EventLog -Source BatteryStatusMonitor -LogName Application
Function OnBatteryStatusChange ($NewStatus) {
If ($NewStatus -eq 1) {
$EventID = 5001
$Message = "The computer was unplugged."
} ElseIf ($NewStatus -eq 2) {
$EventID = 5002
$Message = "The computer was plugged in."
} Else {
$EventID = 5000
$Message = "Battery status changed to $NewStatus"
}
Write-EventLog -LogName Application -Source BatteryStatusMonitor -EventID $EventID -Message $Message
}
$Query = "select * from __instancemodificationevent within 3 where targetinstance isa 'win32_battery' and targetinstance.batterystatus <> previousinstance.batterystatus"
Register-WmiEvent -Query $Query -Action {OnBatteryStatusChange $Event.SourceEventArgs.NewEvent.TargetInstance.BatteryStatus} -SourceIdentifier "BatteryStatusChange"
For (;;) {}