diff --git a/PowerShell/Utilities/Logging/Get-BatteryStatus.md b/PowerShell/Utilities/Logging/Get-BatteryStatus.md index 2a2c7c0..f7e233c 100644 --- a/PowerShell/Utilities/Logging/Get-BatteryStatus.md +++ b/PowerShell/Utilities/Logging/Get-BatteryStatus.md @@ -1,55 +1,141 @@ # Get-BatteryStatus.ps1 ## Overview -**Get-BatteryStatus.ps1** is a PowerShell script for Windows 10/11 that displays your laptop's battery percentage and charging status. The script uses the .NET `System.Windows.Forms` library to access battery information and provides a color-coded status output for quick visual feedback. - -## Features -- **Battery Detection:** Checks if a battery is present on the system. -- **Battery Percentage:** Displays the current battery level as a percentage. -- **Charging Status:** Shows whether the device is plugged in or running on battery. -- **Color-Coded Output:** Uses different colors for different battery levels: - - **Green:** 80% and above - - **Blue:** 50% to 79% - - **Yellow:** 20% to 49% - - **Red:** Below 20% or if no battery detected +**Get-BatteryStatus.ps1** is a PowerShell script for Windows 10/11 that prints a **structured battery analysis report directly in the console**. + +It provides a clear, technician-readable summary of battery health, real-world consumption and runtime estimates — without having to open an HTML file. +All data is sourced from a single **`powercfg /batteryreport`** HTML file generated temporarily at runtime. + +## What it shows + +### Machine identity +- Computer name (from `$env`) +- Computer model (from `SYSTEM PRODUCT NAME` in the powercfg report) +- CPU name (via `Win32_Processor`) + +### Battery information +- **Design capacity** *(factory/original maximum)* in **Wh** +- **Current capacity** *(current maximum)* in **Wh** +- **Battery health (%)** computed from Design vs Current capacity + +### Usage statistics +- Number of **analyzed discharge sessions** (parsed from the powercfg report) +- **Average power consumption** in **Watts** across all sessions + +### Battery life estimation +- **Estimated runtime** with the current battery +- **Estimated runtime** with a new (design capacity) battery + +### Conclusion +- **Wear level (%)** +- Potential **runtime gain** from replacing the battery (in minutes) + +## Data sources +All data comes from a single source: + +| Data | Source | +|---|---| +| Computer name | `$env:COMPUTERNAME` | +| Computer model | `powercfg /batteryreport` HTML (`SYSTEM PRODUCT NAME`) | +| Design / Current capacity | `powercfg /batteryreport` HTML (`Installed batteries` table) | +| Discharge sessions (duration + energy) | `powercfg /batteryreport` HTML (`Battery usage` table) | +| CPU name | `Win32_Processor` (CIM, single call — not in powercfg report) | +| Battery presence | `System.Windows.Forms.SystemInformation.PowerStatus` | + +The script generates a **temporary** HTML file in `%TEMP%`, parses the needed values, then **deletes it immediately**. ## Parameters -This script does **not** take any parameters. +This script does not take any custom parameters. +You can use standard PowerShell common parameters such as: +- `-Verbose` to see the path of the generated report and any internal diagnostic messages. ## Usage ```powershell .\Get-BatteryStatus.ps1 ``` -## Output Example +Verbose mode (recommended for troubleshooting): +```powershell +.\Get-BatteryStatus.ps1 -Verbose ``` -Battery Percentage: 95% (Online) -Battery Percentage: 67% (Offline) -Battery Percentage: 24% (Offline) -Battery Percentage: 8% (Offline) -No battery detected. + +## Output example +```text +==== BATTERY ANALYSIS REPORT ==== + +Computer : HP EliteBook 840 G8 +CPU : Intel Core i5-1135G7 + +Battery information +------------------- +Design Capacity : 53 Wh +Current Capacity : 37 Wh +Battery Health : 70 % + +Usage statistics +---------------- +Analyzed sessions : 34 +Average consumption : 12 W + +Battery life estimation +----------------------- +Estimated runtime (current battery) : 2 h 33 min +Estimated runtime (new battery) : 3 h 43 min + +Conclusion +---------- +Battery wear detected : 24 % + Replacing the battery would increase runtime by ~70 minutes. ``` -## Help & Documentation +## Help & documentation ```powershell Get-Help .\Get-BatteryStatus.ps1 -man .\Get-BatteryStatus.ps1 ``` ## Troubleshooting -- **No Battery Detected:** If you run the script on a desktop or a device without a battery, you'll see "No battery detected." -- **Requires Windows:** The script only works on Windows 10/11 and requires PowerShell 5+. -- **Color Output:** Colors are visible only in terminals that support colored output. + +### "No battery detected" +You are likely running the script on a desktop, a VM, or a device without a battery. + +### "Failed to generate battery report" +`powercfg` requires elevated privileges on some systems. +Try running PowerShell **as Administrator**. + +### Capacity shows "N/A" +The `powercfg /batteryreport` HTML structure may differ on non-English Windows installations. +Run with `-Verbose` to confirm the report was generated, then inspect the HTML file manually before it is deleted (add a breakpoint or comment out the `finally` block temporarily). + +### No discharge sessions found +This can happen if the machine has only been used on AC power recently, or if the battery report does not contain any discharge entries for the last 7 days. + +## Requirements +- Windows 10 / 11 +- PowerShell 5.1 or PowerShell 7+ +- `powercfg.exe` available (built-in on all Windows versions) +- Administrator rights may be required for `powercfg /batteryreport` ## License -``` +```text MIT License Copyright (c) 2025 Miiraak -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. ``` \ No newline at end of file diff --git a/PowerShell/Utilities/Logging/Get-BatteryStatus.ps1 b/PowerShell/Utilities/Logging/Get-BatteryStatus.ps1 index 3c536c1..372e2ad 100644 --- a/PowerShell/Utilities/Logging/Get-BatteryStatus.ps1 +++ b/PowerShell/Utilities/Logging/Get-BatteryStatus.ps1 @@ -2,7 +2,7 @@ # | # ███▄ ▄███▓ ██▓ ██▓ ██▀███ ▄▄▄ ▄▄▄ ██ ▄█▀ | # ▓██▒▀█▀ ██▒▓██▒▓██▒▓██ ▒ ██▒▒████▄ ▒████▄ ██▄█▒ | -# ▓██ ▓██░▒██▒▒██▒▓██ ░▄█ ▒▒██ ▀█▄ ▒██ ▀█▄ ▓███▄░ | +# ▓██ ▓██░▒██▒▒██▒▓██ ░▄█ ▒▒██ ▀█▄ ▒██ ���█▄ ▓███▄░ | # ▒██ ▒██ ░██░░██░▒██▀▀█▄ ░██▄▄▄▄██░██▄▄▄▄██ ▓██ █▄ | # ▒██▒ ░██▒░██░░██░░██▓ ▒██▒ ▓█ ▓██▒▓█ ▓██▒▒██▒ █▄ | # ░ ▒░ ░ ░░▓ ░▓ ░ ▒▓ ░▒▓░ ▒▒ ▓▒█░▒▒ ▓▒█░▒ ▒▒ ▓▒ | @@ -12,51 +12,277 @@ # | # Title : Get-BatteryStatus.ps1 | # Link : https://github.com/Miiraak/Scripts/tree/master/PowerShell/Utilities/Logging/ | -# Version : 1.0 | -# Category : utilities/logging | +# Version : 5.3 | +# Category : utilities/logging | # Target : Windows 10/11 | -# Description : Shows battery percentage and charging status. | -# | +# Description : Battery analysis report - health, consumption & runtime estimate | ######################################################################################## <# .SYNOPSIS - Displays the current battery percentage and charging status. + Displays a structured battery analysis report in the console. .DESCRIPTION - This script checks for battery presence, retrieves the battery percentage and charging status, - and displays the information in a color-coded format: - - Green for 80% or above - - Blue for 50% to 79% - - Yellow for 20% to 49% - - Red for below 20% or if no battery is detected + - Machine identity (computer name, CPU) + - Battery health: Design vs Current capacity, wear % + - Usage statistics: session count + average consumption (W) + - Runtime estimation: current battery vs new battery + - All data sourced from a single powercfg /batteryreport HTML file. + CPU name falls back to Win32_Processor if absent from the report. + +.EXAMPLE + .\Get-BatteryStatus.ps1 .EXAMPLE - .\Get-BatteryStatus.ps1 + .\Get-BatteryStatus.ps1 -Verbose #> -# ---------------[Execution]--------------- # -Add-Type -AssemblyName System.Windows.Forms -$battery = [System.Windows.Forms.SystemInformation]::PowerStatus +[CmdletBinding()] +param() + +#region -- Helpers ---------------------------------------------------------------- + +function Format-Runtime ([double]$Hours) { + if ($Hours -le 0) { return "N/A" } + $h = [int][math]::Floor($Hours) + $m = [int][math]::Round(($Hours - $h) * 60) + if ($m -eq 60) { $h++; $m = 0 } + "{0} h {1:D2} min" -f $h, $m +} + +function Write-Header ([string]$Title) { + Write-Host "" + Write-Host $Title -ForegroundColor White + Write-Host ("-" * $Title.Length) -ForegroundColor DarkGray +} + +function Write-KV ([string]$Key, $Value, [int]$Width = 30) { + if ($null -eq $Value -or "$Value" -eq "") { return } + Write-Host ("{0,-$Width}: {1}" -f $Key, $Value) +} + +# Strips HTML tags and collapses whitespace from a raw cell string +function Strip-Html ([string]$s) { + ($s -replace '<[^>]+>', ' ' -replace '\s+', ' ').Trim() +} + +# Parses "90 005 mWh" or "67 864 mWh" -> int in mWh (removes all non-digits) +function Parse-MWh ([string]$s) { + $clean = $s -replace '[^\d]', '' + if ($clean) { [int]$clean } else { $null } +} + +#endregion + +#region -- powercfg report -------------------------------------------------------- + +function Get-BatteryReportHtml { + $tmp = Join-Path $env:TEMP ("batteryreport_{0}.html" -f [guid]::NewGuid().ToString("N")) + try { + Write-Verbose "Generating: $tmp" + $p = Start-Process powercfg.exe ` + -ArgumentList "/batteryreport /output `"$tmp`"" ` + -Wait -PassThru -NoNewWindow -ErrorAction Stop + if ($p.ExitCode -ne 0 -or -not (Test-Path $tmp)) { + Write-Verbose "powercfg exited $($p.ExitCode) or file missing." + return $null + } + Get-Content $tmp -Raw -ErrorAction Stop + } + catch { + Write-Verbose "powercfg failed: $($_.Exception.Message)" + $null + } + finally { + Remove-Item $tmp -Force -ErrorAction SilentlyContinue + } +} + +#endregion + +#region -- Parsers ---------------------------------------------------------------- + +function Get-MachineInfoFromHtml ([string]$Html) { + # COMPUTER NAME row: COMPUTER NAMEAPOCRYPHA + $computer = if ($Html -match '(?is)COMPUTER\s+NAME\s*\s*]*>\s*([^<]+)') { + $matches[1].Trim() + } else { $env:COMPUTERNAME } + + # SYSTEM PRODUCT NAME row -> this is the machine model, not the CPU + $model = if ($Html -match '(?is)SYSTEM\s+PRODUCT\s+NAME\s*\s*]*>\s*([^<]+)') { + $matches[1].Trim() + } + + # CPU is not in the powercfg report -> single targeted CIM call + $cpu = try { + (Get-CimInstance -ClassName Win32_Processor -ErrorAction Stop | + Select-Object -First 1).Name.Trim() + } catch { "N/A" } + + [pscustomobject]@{ + Computer = if ($model) { $model } else { $computer } + CPU = $cpu + } +} + +function Get-CapacitiesFromHtml ([string]$Html) { + if (-not $Html) { return $null } + + # Target the "Installed batteries" table: + # DESIGN CAPACITY90 005 mWh\n + # FULL CHARGE CAPACITY67 864 mWh\n + $design = if ($Html -match '(?is)DESIGN\s+CAPACITY\s*]*>\s*([\d\s]+)\s*mWh') { + Parse-MWh $matches[1] + } + $full = if ($Html -match '(?is)FULL\s+CHARGE\s+CAPACITY\s*]*>\s*([\d\s]+)\s*mWh') { + Parse-MWh $matches[1] + } + + if (-not $design -and -not $full) { return $null } + [pscustomobject]@{ DesignMWh = $design; FullMWh = $full } +} + +function Get-SessionStats ([string]$Html) { + if (-not $Html) { return $null } + + # Isolate the "Battery usage" table (between the two

tags that surround it) + # Sessions rows have class="dc" and contain: + # 0:16:21 <- duration + # 5 376 mWh <- energy drained + + $watts = foreach ($row in [regex]::Matches($Html, '(?is)]*class="[^"]*dc[^"]*"[^>]*>(.*?)')) { + $inner = $row.Groups[1].Value + + # Duration cell: h:mm:ss + $durMatch = [regex]::Match($inner, '(?is)]*class="[^"]*hms[^"]*"[^>]*>\s*(\d+:\d{2}:\d{2})\s*') + if (-not $durMatch.Success) { continue } -if ($battery.BatteryChargeStatus -eq [System.Windows.Forms.BatteryChargeStatus]::NoBattery) { + # Energy cell: 5 376 mWh + $mwhMatch = [regex]::Match($inner, '(?is)]*class="[^"]*mw[^"]*"[^>]*>\s*([\d\s]+)\s*mWh') + if (-not $mwhMatch.Success) { continue } + + $p = $durMatch.Groups[1].Value -split ':' + $sec = [int]$p[0] * 3600 + [int]$p[1] * 60 + [int]$p[2] + $mWh = Parse-MWh $mwhMatch.Groups[1].Value + + if ($sec -lt 120 -or -not $mWh -or $mWh -le 0) { continue } + + $w = ($mWh / 1000.0) / ($sec / 3600.0) + if ($w -gt 0 -and $w -le 200) { $w } + } + + if (-not $watts) { return $null } + [pscustomobject]@{ + Count = @($watts).Count + AvgWatt = [math]::Round(($watts | Measure-Object -Average).Average, 1) + } +} + +#endregion + +#region -- Battery presence ------------------------------------------------------- + +function Test-BatteryPresent { + Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue + $ps = [System.Windows.Forms.SystemInformation]::PowerStatus + $ps.BatteryChargeStatus -ne [System.Windows.Forms.BatteryChargeStatus]::NoBattery +} + +#endregion + +#region -- Main ------------------------------------------------------------------- + +if (-not (Test-BatteryPresent)) { Write-Host "No battery detected." -ForegroundColor Red - exit + exit 2 +} + +$html = Get-BatteryReportHtml + +if (-not $html) { + Write-Host "Failed to generate battery report. Try running as Administrator." -ForegroundColor Red + exit 1 } -$percentage = [math]::Round($battery.BatteryLifePercent * 100) -$status = $battery.PowerLineStatus +$machineName = $env:COMPUTERNAME +$machine = Get-MachineInfoFromHtml $html +$caps = Get-CapacitiesFromHtml $html +$sessions = Get-SessionStats $html -if ($percentage -ge 80) { - Write-Host "Battery Percentage: $percentage% ($status)" -ForegroundColor Green - exit -} elseif ($percentage -ge 50) { - Write-Host "Battery Percentage: $percentage% ($status)" -ForegroundColor Blue - exit -} elseif ($percentage -ge 20) { - Write-Host "Battery Percentage: $percentage% ($status)" -ForegroundColor Yellow - exit +$designWh = if ($caps -and $caps.DesignMWh) { [int][math]::Round($caps.DesignMWh / 1000) } +$fullWh = if ($caps -and $caps.FullMWh) { [int][math]::Round($caps.FullMWh / 1000) } + +$wearPct = $null +$healthPct = $null +if ($designWh -and $fullWh -and $designWh -gt 0) { + $wearPct = [int][math]::Max(0, [math]::Round((1 - $fullWh / $designWh) * 100)) + $healthPct = 100 - $wearPct +} + +$rtCurrent = $null +$rtNew = $null +$gainMin = $null +if ($sessions -and $sessions.AvgWatt -gt 0) { + if ($fullWh) { $rtCurrent = $fullWh / $sessions.AvgWatt } + if ($designWh) { $rtNew = $designWh / $sessions.AvgWatt } + if ($rtCurrent -and $rtNew) { + $gainMin = [int][math]::Round(($rtNew - $rtCurrent) * 60) + } +} + +#endregion + +#region -- Output ----------------------------------------------------------------- + +Write-Host "" +Write-Host "==== BATTERY ANALYSIS REPORT ====" -ForegroundColor Cyan +Write-Host "" +Write-KV "Report generated" (Get-Date -Format "yyyy-MM-dd HH:mm:ss") +Write-KV "Machine name" $machineName +Write-KV "Computer" $machine.Computer +Write-KV "CPU" $machine.CPU + +Write-Header "Battery information" +Write-KV "Design Capacity" $(if ($designWh) { "$designWh Wh" } else { "N/A" }) +Write-KV "Current Capacity" $(if ($fullWh) { "$fullWh Wh" } else { "N/A" }) +Write-KV "Battery Health" $(if ($null -ne $healthPct) { "$healthPct %" } else { "N/A" }) + +Write-Header "Usage statistics" +if ($sessions) { + Write-KV "Analyzed sessions" $sessions.Count + Write-KV "Average consumption" "$($sessions.AvgWatt) W" +} else { + Write-Host " No discharge sessions found." -ForegroundColor DarkYellow +} + +Write-Header "Battery life estimation" +if ($rtCurrent -or $rtNew) { + Write-KV "Estimated runtime (current battery)" (Format-Runtime $rtCurrent) 38 + Write-KV "Estimated runtime (new battery)" (Format-Runtime $rtNew) 38 +} else { + Write-Host " Insufficient data for runtime estimation." -ForegroundColor DarkYellow +} + +Write-Header "Conclusion" +if ($null -ne $wearPct) { + if ($wearPct -lt 5) { + Write-Host " Battery is in good condition. No replacement needed." -ForegroundColor Green + } else { + Write-KV "Battery wear detected" "$wearPct %" + if ($null -ne $gainMin -and $gainMin -gt 0) { + Write-Host " Replacing the battery would increase runtime by ~$gainMin minutes." + } elseif ($null -ne $gainMin) { + Write-Host " Battery wear present but runtime gain would be negligible." -ForegroundColor DarkYellow + } else { + Write-Host " Could not estimate runtime gain (missing data)." -ForegroundColor DarkYellow + } + } } else { - Write-Host "Battery Percentage: $percentage% ($status)" -ForegroundColor Red - exit -} \ No newline at end of file + Write-Host " Unable to determine battery wear (capacity data unavailable)." -ForegroundColor DarkYellow +} + +Write-Host "" +Write-Host "Tip: run with -Verbose for detailed query information." -ForegroundColor DarkGray +exit 0 + +#endregion \ No newline at end of file