You want to group on userId
- nothing else:
$response = Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/todos' -UseBasicParsing | ConvertFrom-Json
$groupedByUserId = $response |Group-Object -Property userId
This will already give use the correct Count
property, and the Name
property will have the userId
value we're interested in, so all we need to construct is the completed
count:
$groupedWithCounts = $groupedByUserId |Select-Object -Property @{Name='userId';Expression='Name'},@{Name='completed';Expression={@($_.Group |Where-Object completed).Count}},Count
At this point we can sort in the desired order (here by completed
count, then count, then user id):
$sortedGroups = $groupedWithCounts |Sort-Object completed,Count,userId
Putting it all together:
$response = Invoke-WebRequest -Uri 'https://jsonplaceholder.typicode.com/todos' -UseBasicParsing | ConvertFrom-Json
$groupedByUserId = $response |Group-Object -Property userId
$groupedWithCounts = $groupedByUserId |Select-Object -Property @{Name='userId';Expression='Name'},@{Name='completed';Expression={@($_.Group |Where-Object completed).Count}},Count
$sortedGroups = $groupedWithCounts |Sort-Object completed,Count,userId
$sortedGroups |Format-Table
Result:
userId completed Count
------ --------- -----
4 6 20
6 6 20
3 7 20
2 8 20
9 8 20
7 9 20
1 11 20
8 11 20
10 12 20
5 12 20
Much like Select-Object
, Sort-Object
accepts more complex property expressions than just property names:
PS ~> $groupedWithCounts |Sort-Object @{Expression='completed';Descending=$true},{$_.userId -as [long]}
userId completed Count
------ --------- -----
5 12 20
10 12 20
1 11 20
8 11 20
7 9 20
2 8 20
9 8 20
3 7 20
4 6 20
6 6 20