# Exit this script if the current device doesn't have a built-in battery If ( $null -eq (Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue) ) { Microsoft.Powershell.Utility\Write-Output "This endpoint does not have a battery" ; Exit } # Define file paths $Today = Get-LongDate $ReportPathNoExt = "${OutputDirectory}\batteryreport_${Env:COMPUTERNAME}_${Today}" $HtmlReportPath = $ReportPathNoExt + '.html' $XmlReportPath = $ReportPathNoExt + '.xml' # Delete reports if they already exist If ( Test-Path $XmlReportPath ) { Remove-Item -Path $XmlReportPath -Force } If ( Test-Path $HtmlReportPath ) { Remove-Item -Path $HtmlReportPath -Force } # Generate the XML report Write-Output "Generating XML battery report: ${XmlReportPath}" 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 } # Convert XML report to HTML Write-Output "Generating HTML battery report: ${HtmlReportPath}" 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 }