Reputation: 21
I have a set of objects (from an import-csv command) I've grouped on one column. I'm filtering this data based on one of the other columns and trying to get a count.
It works fine until there's a single record in the filtered group set. Then it returns nothing (from what I can tell).
function TestFun ( $data ) {
$data | Group-Object GroupColumn | Sort-Object SortColumn | % {
$currentObj = $_ | Select-Object -ExpandProperty Group
$count1 = ($currentObj | Where-Object { $_.FilterColumn -le 2}).Count
$count2 = ($currentObj | Where-Object { $_.FilterColumn -ge 2}).Count
}
}
That's essentially the code I'm working with, simplified. Like I said, if there's multiple rows ge and/or le 2, it works. If there's only one row, it returns nothing.
I am grouping then expanding the results so that I can iterate through the grouped collection one result at a time.. if there's a better way to do that, I'm open to suggestions. :)
Upvotes: 2
Views: 3515
Reputation: 174990
Use the array subexpression operator @( )
:
$count1 = @($currentObj | Where-Object { $_.FilterColumn -le 2}).Count
$count2 = @($currentObj | Where-Object { $_.FilterColumn -ge 2}).Count
Even if no items slips through the filter, 0
will correctly be returned
Grouping them by the column you see fit is fine, but you may find that Sort-Object SortColumn
doesn't really seem to do anything.
The objects that Group-Object
sends on down the pipeline only have 3 properties (Count
, Name
, Group
) and none of those match the property name SortColumn
, so you might want to move that statement inside the ForEach-Object
loop:
function TestFun {
param(
[array]$data
)
$data | Group-Object GroupColumn | ForEach-Object {
$currentObj = $_ | Select-Object -ExpandProperty Group | Sort-Object SortColumn
$count1 = @($currentObj | Where-Object { $_.FilterColumn -le 2}).Count
$count2 = @($currentObj | Where-Object { $_.FilterColumn -ge 2}).Count
}
}
Upvotes: 3