How can I expand a column from group output?

39 Views Asked by At

I have a list of objects and grouped by a parameter, "off" in this case. Essentially this tells me the total number of users within that office code. What I can't figure out is how I can expand the output to group by other things within each group.

$u = [System.Collections.Generic.List[psobject]]::New()

# users is the response from Get-ADUser
$users | ForEach-Object {

    # enabled and new hold boolean values, I just removed the logic from this example for simplification
    $x = [pscustomobject]@{
        enabled = boolean
        off = [String]$_.o
        new = boolean
    }
    
    $u.Add($x)
}


$u | Group off | Sort Count -Descending

Current output is something like this:


Count    Name    Group
-----    -----   ----------------
  117    Div_A   {@{enabled=True;off=DIV_A,new=False},@{enabled=True;off=DIV_A,new=True}...}
   23    Div_B   {@{enabled=False;off=DIV_B,new=False},@{enabled=True;off=DIV_B,new=False}...}

Essentially what I'd like to do is expand the Group column to instead display a count of 'Enabled' and a count of 'new'. In the end this'll be piped out to a csv. I've tried using foreach-object with another group cmdlet but I get undesirable output which breaks the whole table formatting. I'm not very familiar with intrinsicities of powershell yet.

(im aware using 'new' may be a bad key name to use in practice)

1

There are 1 best solutions below

3
Mathias R. Jessen On BEST ANSWER

You can use Select-Object to calculate new properties:

$u | Group off | Sort Count -Descending |Select Name,Count,@{Name='EnabledCount';Expression={($_.Group |Where-Object Enabled).Count}},@{Name='NewCount';Expression={($_.Group |Where-Object New).Count}}

This will produce new objects each with a Name and Count property with the values copied from the group output, and 2 new properties, each containing a count of objects within the group with the given value set to $true.