2024-02-23 11:49:12 -05:00
# Exit this script if the current device doesn't have a built-in battery
2024-02-27 11:09:13 -05:00
If ( $null -eq ( Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue ) ) { Microsoft . Powershell . Utility \ Write-Output "This endpoint does not have a battery" ; Exit }
2024-02-23 11:49:12 -05:00
# Define file paths
$Today = Get-LongDate
$ReportPathNoExt = " ${OutputDirectory} \batteryreport_ ${Env:COMPUTERNAME} _ ${Today} "
$HtmlReportPath = $ReportPathNoExt + '.html'
$XmlReportPath = $ReportPathNoExt + '.xml'
2024-02-23 11:52:57 -05:00
# Delete reports if they already exist
If ( Test-Path $XmlReportPath ) { Remove-Item -Path $XmlReportPath -Force }
If ( Test-Path $HtmlReportPath ) { Remove-Item -Path $HtmlReportPath -Force }
2024-02-23 11:49:12 -05:00
# Generate the XML report
Write-Output "Generating XML battery report: ${XmlReportPath} "
2026-07-16 10:42:30 -04:00
Try {
$XmlProcess = Start-Process "powercfg.exe" `
-ArgumentList "/batteryreport /output "" ${XmlReportPath} "" /xml" `
-Wait `
-PassThru `
-ErrorAction Stop
}
Catch {
Write-Error $_ . Exception . Message
Exit 1
}
# Make sure powercfg succeeded and actually produced the report
If ( $XmlProcess . ExitCode -ne 0 ) {
Write-Error "powercfg failed to generate the XML battery report with exit code $( $XmlProcess . ExitCode ) "
Exit 1
}
If ( !( Test-Path -LiteralPath $XmlReportPath -PathType Leaf ) ) {
Write-Error "The XML battery report was not created: ${XmlReportPath} "
Exit 1
}
# Validate the generated XML and confirm that it contains battery records
Try {
[ xml ] $GeneratedBatteryReport = Get-Content `
-LiteralPath $XmlReportPath `
-Raw `
-ErrorAction Stop
}
Catch {
Write-Error "The generated battery report is not valid XML: $( $_ . Exception . Message ) "
Exit 1
}
$GeneratedBatteries = @ (
$GeneratedBatteryReport . BatteryReport . Batteries . Battery
)
If ( $GeneratedBatteries . Count -eq 0 ) {
Write-Error "The generated battery report contains no battery records"
Exit 1
}
2024-02-23 11:49:12 -05:00
# Convert XML report to HTML
Write-Output "Generating HTML battery report: ${HtmlReportPath} "
2026-07-16 10:42:30 -04:00
Try {
$HtmlProcess = Start-Process "powercfg.exe" `
-ArgumentList "/batteryreport /transformxml "" ${XmlReportPath} "" /output "" ${HtmlReportPath} """ `
-Wait `
-PassThru `
-ErrorAction Stop
}
Catch {
Write-Error $_ . Exception . Message
Exit 1
}
If ( $HtmlProcess . ExitCode -ne 0 -or !( Test-Path -LiteralPath $HtmlReportPath -PathType Leaf ) ) {
Write-Error "Failed to create the HTML battery report"
Exit 1
}