【问题标题】:Powershell - group array objects by properties and sumPowershell - 按属性和总和对数组对象进行分组
【发布时间】:2021-08-06 19:34:56
【问题描述】:

我正在使用脚本从 CSV 文件中获取一些数据,但不知道解决最重要的部分 - 我有一个包含几百行的数组,这些行中有大约 50 个 Id,每个 Id 都有附加了一些不同的服务。每条线都附有价格。

我想按 ID 和服务对行进行分组,并且我希望将这些组中的每一个都放在某种变量中,这样我就可以对价格求和。我之前在脚本中过滤掉了唯一的 ID 和服务,因为它们总是不同的。

一些示例数据:

$data = @(
[pscustomobject]@{Id='1';Service='Service1';Propertyx=1;Price='5'}
[pscustomobject]@{Id='1';Service='Service2';Propertyx=1;Price='4'}
[pscustomobject]@{Id='2';Service='Service1';Propertyx=1;Price='17'}
[pscustomobject]@{Id='3';Service='Service1';Propertyx=1;Price='3'}
[pscustomobject]@{Id='2';Service='Service2';Propertyx=1;Price='11'}
[pscustomobject]@{Id='4';Service='Service1';Propertyx=1;Price='7'}
[pscustomobject]@{Id='2';Service='Service3';Propertyx=1;Price='5'}
[pscustomobject]@{Id='3';Service='Service2';Propertyx=1;Price='4'}
[pscustomobject]@{Id='4';Service='Service2';Propertyx=1;Price='12'}
[pscustomobject]@{Id='1';Service='Service3';Propertyx=1;Price='8'})  

$ident = $data.Id | select -unique | sort
$Serv = $data.Service | select -unique | sort

我们将不胜感激!

【问题讨论】:

  • 如果您想表达您的感激之情,您可能需要考虑返回并接受(或评论)您过去已经收到的答案,例如this onethis onethis one :)

标签: powershell


【解决方案1】:

使用Group-Object 按一个或多个属性的通用值对对象进行分组。

例如,要计算每个 Id 的总和,请执行以下操作:

$data |Group-Object Id |ForEach-Object {
  [pscustomobject]@{
    Id  = $_.Name
    Sum = $_.Group |Measure-Object Price -Sum |ForEach-Object Sum
  }
}

应该产生如下输出:

Id Sum
-- ---
1   17
2   33
3    7
4   19

【讨论】:

  • 如果我想按两个属性分组怎么办?
  • Group-Object Id 更改为 Group-Object Id,Service - 尽管在您的情况下这没有多大意义,但您的输入中每个不同的 Service/Id 组合只有一个条目:)
猜你喜欢
  • 2015-12-31
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多