PowerShell – How to count objects?



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 {
      Site = $_.Name
      DCs = ($_.Group.Site)

Please help me out. I feel I’m so close to a solution now. 🙂


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{
        site = $_.name
        DCs = $_.group
        count = $_.count

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}}

Answered By – Withholm

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More