I have the following dataset [Array of Hashes]:
$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.
I already tried multiple methods such as piping Group-By
, Group-Object
, Sort-Object
but I'm still not getting the result I want.
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:
$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.
To complement Bacon Bits' helpful answer :
There is no strict need to provide custom objects as input to 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):
$ht = @{}
$dataset | Group-Object { $_.Code } | ForEach-Object { $ht[$_.Name] = $_.Group.Id }
Note the use of { $_.Code }
in lieu of [-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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.