PowerShell/Docs/check-battery.md

81 lines
2.0 KiB
Markdown
Raw Normal View History

2022-12-04 10:40:18 +01:00
## The *check-battery.ps1* Script
2023-05-26 12:20:18 +02:00
This PowerShell script queries the status of the system battery and prints it.
2022-12-04 10:40:18 +01:00
## Parameters
```powershell
2023-05-26 12:20:18 +02:00
/home/mf/Repos/PowerShell/Scripts/check-battery.ps1 [<CommonParameters>]
2022-12-04 10:40:18 +01:00
[<CommonParameters>]
This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction,
WarningVariable, OutBuffer, PipelineVariable, and OutVariable.
```
## Example
```powershell
PS> ./check-battery
2023-05-26 12:20:18 +02:00
✅ 21% battery life, 54 min remaining
2022-12-04 10:40:18 +01:00
```
## Notes
Author: Markus Fleschutz | License: CC0
## Related Links
https://github.com/fleschutz/PowerShell
## Source Code
```powershell
<#
.SYNOPSIS
2023-05-26 12:20:18 +02:00
Checks the battery
2022-12-04 10:40:18 +01:00
.DESCRIPTION
2023-05-26 12:20:18 +02:00
This PowerShell script queries the status of the system battery and prints it.
2022-12-04 10:40:18 +01:00
.EXAMPLE
PS> ./check-battery
2023-05-26 12:20:18 +02:00
✅ 21% battery life, 54 min remaining
2022-12-04 10:40:18 +01:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
try {
if ($IsLinux) {
2023-05-26 12:20:18 +02:00
$Reply = "✅ AC powered" # TODO, just guessing :-)
2022-12-04 10:40:18 +01:00
} else {
Add-Type -Assembly System.Windows.Forms
$Details = [System.Windows.Forms.SystemInformation]::PowerStatus
2023-05-26 12:20:18 +02:00
[int]$Percent = 100 * $Details.BatteryLifePercent
[int]$Remaining = $Details.BatteryLifeRemaining / 60
2022-12-04 10:40:18 +01:00
switch ($Details.PowerLineStatus) {
2023-05-26 12:20:18 +02:00
"Online" {
if ($Details.BatteryChargeStatus -eq "NoSystemBattery") {
$Reply = "✅ AC powered"
} elseif ($Percent -eq 100) {
$Reply = "✅ Battery $Percent% full"
} else {
$Reply = "✅ Battery $Percent%, charging..."
}
}
"Offline" {
if ($Percent -eq 100) {
$Reply = "✅ $Percent% full battery, $Remaining min remaining"
} elseif ($Remaining -gt 30) {
$Reply = "✅ $Percent% battery life, $Remaining min remaining"
} else {
$Reply = "⚠️ $Percent% battery life, only $Remaining min remaining"
}
}
2022-12-04 10:40:18 +01:00
}
}
2023-05-26 12:20:18 +02:00
Write-Host $Reply
2022-12-04 10:40:18 +01:00
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}
```
*Generated by convert-ps2md.ps1 using the comment-based help of check-battery.ps1*