PowerShell - How to count objects?

Viewed 449

I am using PowerShell to build some scripts in an Active Directory enviroment and am currently struggling to find a way to count objects. My base search is:

$DClist = (Get-ADForest).Domains | % { Get-ADDomainController –Filter * -Server $_ } | Select Site, Name, Domain

And it generates the following output:

Site        Name      Domain      
----        ----      ------      
Site-A      DC-123    acme.local
Site-A      DC-ABC    acme.local
Site-B      DC-XYZ    domain.local
Site-C      DC-YPT    domain.local 

Now I would like to count the number of objects in the column 'Name' and display something like this:

Site        Count_of_Name        
----        ----       
Site-A      2
Site-B      1
Site-C      1

I have already tried a lot of things and the closest I got so far was using:

$DcList | Group-Object Site

But unfortunately it is not the right way to go as it only counts the number of 'Site' and "ignores" the rest. Also tried this, but it did not work as I expect either:

$DcList | Group-Object Site, Name

Please help me figure out the logic of this.

********************** UPDATE **********************

I have finally been able to come to this, but I cannot figure out a way to count the objects from 'Site' column:

$DClist | Group-Object -Property Site | ForEach-Object -Process {
    [PSCustomObject]@{
      Site = $_.Name
      DCs = ($_.Group.Site)
    }
} 

Please help me out. I feel I'm so close to a solution now. :)

2 Answers

you are REALLY close, and the answer is about what you would expect :) when doing group you automatically get a count property. just use this.

$DClist = (Get-ADForest).Domains | % { Get-ADDomainController –Filter * -Server $_ } | Select Site, Name, Domain
$dclist|Group-Object site|ForEach-Object{
    [PSCustomObject]@{
        site = $_.name
        DCs = $_.group
        count = $_.count
    }
}

edit: you could also do this that could be even faster if propegating through many objects. when doing select you can add a custom query and a label for that query. @{name='fieldname';expression={$_.reference.to.object}} or @{n='field';e={$_.expression}} if you want to shorten it.

$dclist|Group-Object site|ForEach-Object{
    $_|select @{n='site';e={$_.name}},count,@{n='DCs';e={$_.group}}
}

I don't exactly understand what you really want, but if it is some kind of tree, this will show it:

ForEach($Site in ($dclist | Group-Object site))
{
  $Site.Count.ToString() + " " + $Site.Name 
  
  ForEach($Server in $Site.Group)
  {
    "  + " + $Server.Name
  }
}

Output:

2 Site-A
  + DC-123
  + DC-ABC
1 Site-B
  + DC-XYZ
1 Site-C
  + DC-YPT
Related