Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
PowerShell script to help to keep laptop battery level in the specified range. Not automatically! You need to plug-in or unplug cable when you hear alert sound :) See: http://www.mmdemirbas.com/2013/03/monitor-remaining-battery-level-using.html
#########################################################################
# #
# Script to check battery state periodically and alert if it is #
# going to outside of the desired range (%40-%80) by default. #
# #
# Usage: #
# #
# # To alert if x<=40 or x>=80, and check each 15 sec #
# #
# .\battery.ps1 40 80 15 #
# #
# #
# Author: Muhammed Demirbas, mmdemirbas at gmail dot com #
# #
# Date : 2013-03-26 #
# #
#########################################################################
# Default values for parameters
param($lowerLimit=40, $upperLimit=80, $interval=15)
# Function to return first non-null value among its arguments
Function IfNull($a,$b) { if($a){$a} else {$b} }
while($true)
{
$obj = (Get-WmiObject -Class Win32_Battery -ea 0)
$remainingMinutes = IfNull $obj.EstimatedRuntime "N/A"
$remainingPercentage = IfNull $obj.EstimatedChargeRemaining "N/A"
$statusString = switch (IfNull $obj.BatteryStatus 0)
{
0 { $pluggedin=0 ; "N/A" }
1 { $pluggedin=0 ; "Discharging" }
2 { $pluggedin=1 ; "Plugged in to AC" }
3 { $pluggedin=0 ; "Fully Charged" }
4 { $pluggedin=0 ; "Low" }
5 { $pluggedin=0 ; "Critical" }
6 { $pluggedin=1 ; "Charging" }
7 { $pluggedin=1 ; "Charging and High" }
8 { $pluggedin=1 ; "Charging and Low" }
9 { $pluggedin=1 ; "Charging and Critical" }
10 { $pluggedin=0 ; "Unknown State" }
11 { $pluggedin=0 ; "Partially Charged" }
}
if ($remainingMinutes -ge 1000) { $remainingMinutes = "N/A" }
if ( !$pluggedin -and $remainingPercentage -le $lowerLimit ) { $alert = "Connect AC!" }
elseif ( $pluggedin -and $remainingPercentage -ge $upperLimit ) { $alert = "Disconnect AC!" }
else
{
$alert = $null
}
$forecolor = if($alert){ [ConsoleColor]::White } else { [ConsoleColor]::Gray }
$backcolor = if($alert){ [ConsoleColor]::DarkRed } else { [ConsoleColor]::DarkGreen }
$log = "[$(Get-Date)] Remaining: $remainingPercentage% ~= $remainingMinutes minutes. $statusString. $alert"
Write-Host -ForegroundColor $forecolor -BackgroundColor $backcolor $log
if ($alert)
{
[System.Media.SystemSounds]::Hand.Play() # Play sound
}
Start-Sleep -Seconds $interval
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment