flenwan
November 5, 2021, 3:55pm
#1
I have a dataset that I get the unique values of an OrderID from. Then I need to get the set of items from each OrderID. The output of my code is returning the unique OrderID list instead of the set.
$orderIdList = $packageItems.Tables.Rows.Orderid | Sort-Object | Get-Unique
foreach ($item in $orderIdList) {
$itemGroup = $orderIdList | Where-Object {$orderIdList -contains $item}
}
$orderIdList
is just a list of unique order IDs - that’s what your first command is doing.
$itemGroup = $orderIdList | Where-Object {$orderIdList -contains $item}
Presumably, $orderIdList
in the above statement should refer to something else?
Think you should take a look at Group-Object:
$grpOrders = $packageItems.Tables.Rows | Group-Object -Property OrderId
Here is a basic example:
$orders = @"
OrderId,Customer,Item
4567,jsmith@company.org,Shoes 10.5
4570,tommy@anothercomp.com,Shirt XL
4567,jsmith@company.org,Shirt XL
4561,sally@company.org,Pants Small
4567,jsmith@company.org,Pant XL
"@ | ConvertFrom-Csv
$grpOrders = $orders | Group-Object -Property OrderId
foreach ($order in $grpOrders) {
'Processing order {0} with {1} items' -f $order.Name, $order.Count
foreach ($orderItem in $order.Group) {
'Processing item {0}' -f $orderItem.Item
}
}
Output:
PS C:\Users\rasim> $grpOrders
Count Name Group
----- ---- -----
1 4561 {@{OrderId=4561; Customer=sally@company.org; Item=Pants Small}}
3 4567 {@{OrderId=4567; Customer=jsmith@company.org; Item=Shoes 10.5}, @{OrderId=4567; Customer=jsmith@company.org; Item=Shirt XL}, @{OrderId=4…
1 4570 {@{OrderId=4570; Customer=tommy@anothercomp.com; Item=Shirt XL}}
PS C:\Users\rasim> c:\Users\rasim\Desktop\temp.ps1
Processing order 4561 with 1 items
Processing item Pants Small
Processing order 4567 with 3 items
Processing item Shoes 10.5
Processing item Shirt XL
Processing item Pant XL
Processing order 4570 with 1 items
Processing item Shirt XL
1 Like
flenwan
November 5, 2021, 4:29pm
#4
Yes, my bad, I got mixed up when modifying the code to post. I was using $packageItems.Tables.Rows.Orderid but it still returns all records instead of the $item value.
flenwan
November 5, 2021, 5:04pm
#5
Thank you rob-simmers, that is a very elegant solution!