CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Using Group-Object on Complex Nested Data Structures

๐Ÿ‘€ Views: 81 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-09
powershell group-object pscustomobject PowerShell

I've searched everywhere and can't find a clear answer... I'm working with a collection of complex objects in PowerShell 7.3 where I need to group data based on multiple properties. My data structure is a list of custom objects representing sales records, and I want to group them by both 'Region' and 'ProductCategory'. However, I encounter an unexpected scenario when trying to use `Group-Object`. Hereโ€™s a simplified version of my data: ```powershell $salesRecords = @( [PSCustomObject]@{ Region = 'North'; ProductCategory = 'Electronics'; Amount = 200 }, [PSCustomObject]@{ Region = 'North'; ProductCategory = 'Clothing'; Amount = 150 }, [PSCustomObject]@{ Region = 'South'; ProductCategory = 'Electronics'; Amount = 300 }, [PSCustomObject]@{ Region = 'South'; ProductCategory = 'Clothing'; Amount = 100 }, [PSCustomObject]@{ Region = 'North'; ProductCategory = 'Electronics'; Amount = 50 } ) ``` Iโ€™m trying to group the records like this: ```powershell $groupedSales = $salesRecords | Group-Object -Property Region, ProductCategory ``` But instead of getting a clear grouping, I receive a cryptic behavior that says: ``` The property 'Region, ProductCategory' does not exist on type 'PSCustomObject'. ``` Iโ€™ve confirmed that both properties exist in my custom objects. I suspect it might be related to how Iโ€™m using multiple properties in the `Group-Object` cmdlet. After some experimentation, I tried grouping by a single property, and that works perfectly. However, Iโ€™m not sure how to proceed with grouping by both properties without running into this scenario. Any insights on how to correctly group my sales records by multiple properties? A workaround suggestion would also be welcomed if direct grouping isnโ€™t feasible. I recently upgraded to Powershell 3.11. Thanks for your help in advance! What's the correct way to implement this?