Question: How do I write this so it gives the same result in v4 and v5?
I am trying to group the following dataset by SiteCode.
I have a dataset as follows [Array of Hashes]:
Assume AppointmentId is always unique
$groupedDataset = @{}
$dataset = @(
@{
Program = "x"
AppointmentId = "1234567891"
AdminDate = "x"
CountryName = "x"
SiteCode = "x1111"
DateRequested = "x"
SubjectID = "x"
AccountID = "x"
},
@{
Program = "x"
AppointmentId = "1234567892"
AdminDate = "x"
CountryName = "x"
SiteCode = "x1112"
DateRequested = "x"
SubjectID = "x"
AccountID = "x"
},
@{
Program = "x"
AppointmentId = "1234567893"
AdminDate = "x"
CountryName = "x"
SiteCode = "x1113"
DateRequested = "x"
SubjectID = "x"
AccountID = "x"
},
@{
Program = "x"
AppointmentId = "1234567894"
AdminDate = "x"
CountryName = "x"
SiteCode = "x1111"
DateRequested = "x"
SubjectID = "x"
AccountID = "x"
}
)
When I run the following code below in PS Version: 5.1
$dataset |
ForEach-Object { [PSCustomObject]$_ } |
Group-Object -Property SiteCode |
ForEach-Object {
$groupedDataset[$_.Name] = $_.Group
}
It returns the result I require:
Name Value
---- -----
x1113 {@{SiteCode=x1113; Program=x; Appointment...
x1111 {@{SiteCode=x1111; Program=x; Appointment...
x1112 {@{SiteCode=x1112; Program=x; Appointment...
When I run the exact code in
PS Version: 4.0 it returns the following:
Name Value
---- -----
{System.Collections.Hashtable, System.Collect...
In PowerShell v5.0 improvements have been made, eg. PSCustomObject casting, which is in your script
Try doing it the old school way and instead of building a hashtable yourself, use the one returned by the groupby.
This results in