Recipes by topic

Battery status

Win32_Battery returns one instance per battery. A desktop has none: the query then returns nothing.

$statusName = @{
    1  = 'Discharging'
    2  = 'On AC'
    3  = 'Fully charged'
    4  = 'Low'
    5  = 'Critical'
    6  = 'Charging'
    7  = 'Charging, high'
    8  = 'Charging, low'
    9  = 'Charging, critical'
    11 = 'Partially charged'
}

$battery = @(Get-CimInstance -ClassName Win32_Battery)

if ($battery.Count -eq 0) {
    Write-Warning -Message 'No battery found.'
} else {
    $battery |
        Select-Object -Property @(
            'Name'
            'EstimatedChargeRemaining'
            @{ Name = 'Status'; Expression = { $statusName[[int]$_.BatteryStatus] } }
            @{
                Name       = 'RunTimeMinutes'
                Expression = { if ($_.EstimatedRunTime -ne 71582788) { $_.EstimatedRunTime } }
            }
        )
}

EstimatedChargeRemaining is a percentage. EstimatedRunTime is 71582788 when the machine runs on AC power: the script replaces it with an empty value. On many laptops DesignCapacity and FullChargeCapacity are not filled in this class; wear is then read from the classes in the root/wmi namespace.

Variant: remote

Machines without a battery produce no row.

$cimSession = New-CimSession -ComputerName 'LAPTOP01', 'LAPTOP02'
try {
    $cimParameters = @{
        CimSession = $cimSession
        ClassName  = 'Win32_Battery'
    }
    Get-CimInstance @cimParameters |
        Select-Object -Property PSComputerName, EstimatedChargeRemaining, BatteryStatus
} finally {
    Remove-CimSession -CimSession $cimSession
}

Classes used

← All recipes