简体   繁体   English

有“Sum”功能吗?

[英]Is there a “Sum” function?

I've got following code snippet: 我有以下代码片段:

> 1..10|%{$count=0}{$count+=$_}{$count}
55
> 1..10|Sum

The last line obviously shows an error since there is no "Sum" function. 最后一行显然显示错误,因为没有“Sum”功能。 Is there a convenient way to sum items in PowerShell? 有没有一种方便的方法来汇总PowerShell中的项目?

You can use the Measure-Object cmdlet : 您可以使用Measure-Object cmdlet

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: 请注意,它也适用于对象的属性:

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 . 在上面的示例中,我们通过将-Property参数设置为Length来对数组中字符串的长度求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM