Skip to content

Instantly share code, notes, and snippets.

@todiadiyatmo
Last active November 11, 2024 04:56
Show Gist options
  • Save todiadiyatmo/bf80e3e797e092375f7a3a82e9001110 to your computer and use it in GitHub Desktop.
Save todiadiyatmo/bf80e3e797e092375f7a3a82e9001110 to your computer and use it in GitHub Desktop.
Battery Monitor
$dischargeHistory = @()
$previousChargingState = $null
while ($true) {
$battery = Get-WmiObject Win32_Battery
if ($battery) {
$batteryLevel = $battery.EstimatedChargeRemaining
# Get current discharge rate
$dischargerate = Get-WmiObject -Class "BatteryStatus" -Namespace "root\wmi"
$rate = [math]::Abs($dischargerate.DischargeRate)
$rateInMw = ($rate/1000)
# Check if charging state changed
$currentChargingState = $dischargerate.DischargeRate -gt 0
if ($previousChargingState -ne $null -and $previousChargingState -ne $currentChargingState) {
$dischargeHistory = @() # Reset history when state changes
}
$previousChargingState = $currentChargingState
$dischargeHistory += $rateInMw
# Calculate average
$averageRate = ($dischargeHistory | Measure-Object -Average).Average
# Calculate remaining time based on average discharge rate
$designCapacity = (Get-WmiObject -Class "BatteryFullChargedCapacity" -Namespace "root\wmi").FullChargedCapacity
$currentCapacity = ($designCapacity * $batteryLevel) / 100
if ($averageRate -gt 0) {
$remainingMinutes = ($currentCapacity / ($averageRate * 1000)) * 60
$hours = [math]::Floor($remainingMinutes / 60)
$minutes = [math]::Floor($remainingMinutes % 60)
$timeEstimate = "$hours hours $minutes minutes"
} else {
$timeEstimate = "Calculating..."
}
Clear-Host
Write-Host "Battery Level: $batteryLevel%"
Write-Host "Current Discharge Rate: $($rateInMw.ToString("F1"))mW"
Write-Host "Average Discharge Rate: $($averageRate.ToString("F1"))mW"
if ($dischargerate.DischargeRate -gt 0) {
Write-Host "Estimated Time: $timeEstimate"
} else {
Write-Host "Estimated Time: Charging"
}
}
else {
Write-Host "No battery detected"
}
Start-Sleep -Seconds 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment