问题:如何编写此内容以便在v4和v5中提供相同的结果?
我正在尝试按SiteCode
分组以下数据集。
我有一个数据集如下[哈希数组]:
假设AppointmentId
始终是唯一的
$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"
}
)
当我在PS Version: 5.1
$dataset |
ForEach-Object { [PSCustomObject]$_ } |
Group-Object -Property SiteCode |
ForEach-Object {
$groupedDataset[$_.Name] = $_.Group
}
它返回我需要的结果:
Name Value
---- -----
x1113 {@{SiteCode=x1113; Program=x; Appointment...
x1111 {@{SiteCode=x1111; Program=x; Appointment...
x1112 {@{SiteCode=x1112; Program=x; Appointment...
<小时/> 当我在
PS Version: 4.0
中运行完全代码时,它会返回以下内容:
Name Value
---- -----
{System.Collections.Hashtable, System.Collect...
答案 0 :(得分:3)
在PowerShell v5.0中已经进行了改进,例如。 PSCustomObject转换,在您的脚本中
ForEach-Object { [PSCustomObject]$_ }
尝试以旧学校的方式进行,而不是自己构建哈希表,使用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
这导致
$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}