Summing Up Multiple Objects

by Jul 3, 2009

PowerShell is a dynamic language, and as Forest Gump put it, you never know what you get. For example, when you try and figure out the battery charge on a notebook, the following command may return null, one or multiple results depending on the number of batteries in your system:

Get-WMIObject Win32_Battery

To find out the overall charge of all batteries in your system, simply use Measure-Object. Measure-Object happily accepts an arbitrary number of (equal) objects and aggregates information. To find out the overall charge remaining in all of your batteries, use this:

Get-WMIObject Win32_Battery | Measure-Object EstimatedChargeRemaining -average
(Get-WMIObject Win32_Battery |
Measure-Object EstimatedChargeRemaining -average).Average

Note that this call will fail if there is no battery at all in your system because then Measure-Object is unable to find a EstimatedchargeRemaining property.