gpt4 book ai didi

powershell - 寻求快速,简洁和清晰的代码的平衡组合,以从对象数组中累加值

转载 作者:行者123 更新时间:2023-12-03 00:47:12 25 4
gpt4 key购买 nike

给定以下对象数组:

Email               Domain       Tally
----- ----- -----
email1@domainA.com domainA.com 4
email1@domainB.com domainB.com 1
email2@domainC.com domainC.com 6
email4@domainA.com domainA.com 1

我想对Domain进行“分组”,并在进行时加起来Tally。最终结果是这样的:
Domain       Tally
------ -----
domainA.com 5
domainB.com 1
domainC.com 6

我有一些有效的方法,但我觉得它过于复杂。
$AllTheAddresses = Get-AllTheAddresses

$DomainTally = @()
foreach ($Addy in $AllTheAddresses)
{
if ($DomainTally | Where-Object {$_.RecipientDomain -eq $Addy.RecipientDomain})
{
$DomainTally |
Where-Object {$_.RecipientDomain -eq $Addy.RecipientDomain} |
ForEach-Object {$_.Tally += $Addy.Tally }
}
else
{
$props = @{
RecipientDomain = $Addy.RecipientDomain
Tally = $Addy.Tally
}
$DomainTally += New-Object -TypeName PSObject -Property $props
}
}

最佳答案

在我的示例中,我将地址创建为哈希表,但是PowerShell将允许您通过.Property类似于对象来引用键。

如果您真的只是按域求和,那么似乎不需要任何比HashTable复杂的事情来创建运行总计。

基本总结:

$Tally = @{}
$AllTheAddresses | ForEach-Object {
$Tally[$_.Domain] += $_.Tally
}

使用此样本数据...
$AllTheAddresses = @( 
@{ Email = "email1@domainA.com"; Domain = "domainA.com"; Tally = 4 };
@{ Email = "email1@domainB.com"; Domain = "domainB.com"; Tally = 1 };
@{ Email = "email1@domainC.com"; Domain = "domainC.com"; Tally = 6 };
@{ Email = "email1@domainA.com"; Domain = "domainA.com"; Tally = 1 }
)

然后您得到以下输出:
PS> $tally
Name Value
---- -----
domainC.com 6
domainB.com 1
domainA.com 5

关于powershell - 寻求快速,简洁和清晰的代码的平衡组合,以从对象数组中累加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com