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...
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
ForEach-Object { [PSCustomObject]$_ }
Try doing it the old school way and instead of building a hashtable yourself, use the one returned by the groupby.
$groupedDataset = $dataset |
ForEach-Object {
[PSCustomObject]@{
Program = $_.Program
AppointmentId = $_.AppointmentId
AdminDate = $_.AdminDate
CountryName = $_.CountryName
SiteCode = $_.SiteCode
DateRequested = $_.DateRequested
SubjectID = $_.SubjectID
AccountID = $_.AccountID
}
} |
Group-Object -Property SiteCode -AsHashTable
This results in
$groupedDataset | out-host
Count Name Group
----- ----- ------
2 x1111 {@{Program=x; AppointmentId=1234567891; AdminDate=x; CountryName=x; SiteCode=x1111; DateRequested=x; SubjectID=x; AccountID=x}, @{Program=x; AppointmentId=1234567894; AdminDate=x; CountryN...
1 x1112 {@{Program=x; AppointmentId=1234567892; AdminDate=x; CountryName=x; SiteCode=x1112; DateRequested=x; SubjectID=x; AccountID=x}}
1 x1113 {@{Program=x; AppointmentId=1234567893; AdminDate=x; CountryName=x; SiteCode=x1113; DateRequested=x; SubjectID=x; AccountID=x}