Question:
I’ve got following code snippet:
1 2 3 4 |
> 1..10|%{$count=0}{$count+=$_}{$count} 55 > 1..10|Sum |
The last line obviously shows an error since there is no “Sum” function. Is there a convenient way to sum items in PowerShell?
Answer:
You can use the Measure-Object
cmdlet:
1 2 3 4 5 6 7 8 9 10 11 |
PS > 1..10 | Measure-Object -Sum Count : 10 Average : Sum : 55 Maximum : Minimum : Property : PS > (1..10 | Measure-Object -Sum).Sum 55 PS > |
Note that it also works with properties of objects:
1 2 3 4 5 6 7 8 9 |
PS > ('abc', 'def', 'ghi') | Measure-Object -Sum -Property Length Count : 3 Average : Sum : 9 Maximum : Minimum : Property : Length PS > |
In the above example, we sum the lengths of the strings in the array by setting the -Property
parameter to Length
.