About this article
This article was created using an automated generation workflow leveraging generative AI. Based on the Win32GetSystemPowerStatusspecification in Microsoft Learn, it is organized as a smoke test to read the power status once via P/Invoke from PowerShell.
Verification Status: 📘 Microsoft official specification verified, Windows physical device unverified
The success criteria for this TRY are:That the Win32 API call succeeds and can display the AC power status and battery level values.No configuration changes will be made.
Smoke Test
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class PowerStatusNative {
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_POWER_STATUS {
public byte ACLineStatus; public byte BatteryFlag; public byte BatteryLifePercent; public byte SystemStatusFlag;
public uint BatteryLifeTime; public uint BatteryFullLifeTime;
}
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool GetSystemPowerStatus(out SYSTEM_POWER_STATUS s);
}
'@
$s = New-Object PowerStatusNative+SYSTEM_POWER_STATUS
if ([PowerStatusNative]::GetSystemPowerStatus([ref]$s)) { "[SUCCESS] ACLineStatus=$($s.ACLineStatus) Battery=$($s.BatteryLifePercent)%" }
else { "[FAILED] Win32Error=$([Runtime.InteropServices.Marshal]::GetLastWin32Error())" }
Observe
ACLineStatus is 0/1/255, etc., and BatteryLifePercent is 0 to 100, or 255 if unknown.Not displaying 255 as 255% is important.
Why — Why we can call the Win32 API even in PowerShell
Add-Type compiles a small C# declaration and calls the kernel32.dll function via P/Invoke. Even if PowerShell cmdlets do not have the desired information, you can reach native Windows APIs.
Change one thing
If using a laptop where you can connect/disconnect the AC adapter, change only that physical condition and ACLineStatus observe the difference.
Failure / Boundary
Even if the API succeeds, not all fields contain meaningful values. Distinguish unknown values, absence of a battery, and virtual environments; do not judge a failure based on a single reading.
For professional use
It can be used as an entry point for help desks to check AC connectivity and battery level availability during simple diagnostics of conference room PCs or portable devices.
