Search code examples
powershellvariablescalculation

How do I create a script in powershell that grabs two values and then divides them and outputs the result?


I just want to see how my different chargers charge my laptop and learn something as well. This is the code I'm currently running in the script.

gwmi -Class batterystatus -Namespace root\wmi | Select-Object -Property ChargeRate, Voltage, DischargeRate, RemainingCapacity

I'd like to get the value in mAh for charging which I can get by dividing the mWh chargerate value with voltage value, but I have no clue where to even begin. First of all I'd need to get a voltage number with a decimal and not in the shape it outputs it. I'd like the output in mAh to be right next to the Remaining capacity with the name "ChargeRate mAh" in the same style as the other ones. I've provided the image of the current output. Is this achievable?

Script output:

Script output

I've looked on google and looked for code that might help me, but without any knowledge of powershell, I couldn't get any use from it.


Solution

  • You are on the right track. Can you see if powercfg satisfies your needs? https://davejlong.com/getting-battery-health-with-powershell/ It will produce an HTML report.

    See: https://powershell.one/wmi/root/cimv2/win32_battery

    If you need to use PowerShell lets build on top of your current script:

    Get-WmiObject -Class batterystatus -Namespace root\wmi | Select-Object ChargeRate, Voltage, DischargeRate, RemainingCapacity, @{Name='ChargeRate mAh'; Expression={if ($_.Voltage -ne 0) { $_.ChargeRate / ($_.Voltage / 1000) } else { 0 }}}
    

    Here we are doing the calculations directly in the command. The if statement is a check to ensure we don't do division by 0.

    EDIT: As @Darin mentioned, each battery will have different properties, not all Properties are available for all batteries. You will have to tweak this script to your batteries properties.

    Test this and let me know if it helps.