简体   繁体   English

Powershell Group具有重复项的哈希数组

[英]Powershell Group Array of Hashes with Duplicates

I have the following dataset [Array of Hashes]: 我有以下数据集[哈希数组]:

Assume ID is always unique 假设ID始终是唯一的


$dataset = @(
    @{
        ID   = "1234567891"
        Code = "ABC1111"
    },
    @{
        ID   = "1234567892"
        Code = "ABC1111"
    },
    @{
        ID   = "1234567893"
        Code = "ABC1112"  
    },
    @{
        ID   = "1234567894"
        Code = "ABC1113"   
    },
    @{
        ID   = "1234567895"
        Code = "ABC1114"   
    },
    @{
        ID   = "1234567896"
        Code = "ABC1111"  
    }
)

What I am trying to do is to group the following dataset by Code key. 我想要做的是按Code键对以下数据集进行分组。

I already tried multiple methods such as piping Group-By , Group-Object , Sort-Object but I'm still not getting the result I want. 我已经尝试了多种方法,例如管道Group-ByGroup-ObjectSort-Object但我仍然没有得到我想要的结果。

What result I am looking to return is a hashtable which looks like so [Or anything similar]: 我希望返回的结果是一个哈希表,看起来像[或类似的东西]:

$groupedDataset = @{
    ABC1111 = @("1234567891","1234567892","1234567896")
    ABC1112 = @("1234567893")
    ABC1113 = @("1234567894")
    ABC1114 = @("1234567895")
}

Convert the hash tables to a PSCustomObjects, group it, then assign it to the new hash table: 将哈希表转换为PSCustomObjects,对其进行分组,然后将其分配给新的哈希表:

$groupedDataset = @{}

$dataset |
    ForEach-Object { [PSCustomObject]$_ } |
    Group-Object -Property Code |
    ForEach-Object { $groupedDataset[$_.Name] = $_.Group.ID }

See Get-Help about_Object_Creation for more information about using [PSCustomObject] to create custom objects from hash tables. 有关使用[PSCustomObject]从哈希表创建自定义对象的更多信息,请参阅Get-Help about_Object_Creation

To complement Bacon Bits' helpful answer : 补充培根比特的有用答案

There is no strict need to provide custom objects as input to Group-Object ; 没有严格要求提供自定义对象作为Group-Object输入; [hashtable] instances can be used as-is, as long as you use a script-block argument to access the entry to group by (PSv3+ syntax): [hashtable]实例可以按原样使用,只要您使用script-block参数来访问要分组的条目(PSv3 +语法):

$ht = @{}
$dataset | Group-Object { $_.Code } | ForEach-Object { $ht[$_.Name] = $_.Group.Id }

Note the use of { $_.Code } in lieu of [-Property] Code ; 注意使用{ $_.Code } [-Property] Code { $_.Code }代替[-Property] Code ; the latter only works with bona fide properties (as opposed to hashtable entries; conversely, however, { $_.Code } works in either scenario, though Code , if applicable, is faster). 后者仅适用于真正的属性 (与哈希表条目相反;相反, { $_.Code }适用于任一情况,但Code (如果适用)更快)。

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

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