Triggering tasks and running programs when Windows 7 is plugged in or unplugged?

5,751

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 (;;) {}
Share:
5,751

Related videos on Youtube

William C
Author by

William C

Updated on September 18, 2022

Comments

  • William C
    William C over 1 year

    Possible Duplicate:
    Is there a way to execute a program on power events?

    Is there a Windows event that I can watch in Task Scheduler that will trigger when the power is plugged in? And an event when the power is unplugged?

    I want to start and stop CrashPlan while on battery power. (This has been a 2.5-year-old feature request in CrashPlan and honestly I can't wait for them to add it.)

    Others have also asked previously how to disable SuperFetch and Search Indexing on battery power. I think this trick will solve these questions, too.

    Is there such a windows event? If not, could there be a program that I can install that detects power changes, which then I can create a Task Scheduler trigger for.

  • Kevin Jin
    Kevin Jin over 6 years
    If the only event OP wants to capture is a change in the AC charger status through the Win32 API, he can simply handle PBT_APMPOWERSTATUSCHANGE events through the SERVICE_CONTROL_POWEREVENT control code in the HandlerEx callback to RegisterServiceCtrlHandlerEx, or the WM_POWERBROADCAST message in WindowProc. This should be supported by Windows XP and later. However, he asked for an Windows Event.