PowerShell: Provide a listing and count of computers in an OU structure

Today I had to quickly figure out how many server computer accounts we had in AD. We have an OU structure like domain/servers/location1, domain/servers/location2, etc

This is how I did it:

# Assumes a CanonicalName of server accounts like example.org/servers//
# This groups the results of Get-ADComputer on the  element of the CName
Get-ADComputer -SearchBase "OU=servers,DC=example,DC=org" -Filter {Enabled -eq $true} -Properties CanonicalName | Group-Object {($_.CanonicalName -Split "/")[2]}

That results in the following output:

Count Name                      Group
----- ----                      -----
   43 Sydney                    {blah}
    8 Adelaide                  {blah}
    8 Brisbane                  {blah}
    5 Hobart                    {blah}
   17 Perth                     {blah}
   39 Melbourne                 {blah}
   10 Canberra                  {blah}

May 2017 update

I noticed that some people are hitting this site when googling “how to get count of computers in AD in an OU“.

Counting the number of computer objects in a single OU is simple:

Get-ADComputer -SearchBase "OU=Computers,DC=contoso,DC=com" -Filter * | Measure-Object

Here is how I’d count the number of computer objects in multiple OUs that aren’t under a common parent OU:

$orgUnits = 'OU=Workstations,DC=contoso,DC=com','OU=Servers,DC=contoso,DC=com'
$orgUnits | ForEach-Object {Get-ADComputer -SearchBase $_ -Filter *} | Measure-Object

4 thoughts on “PowerShell: Provide a listing and count of computers in an OU structure

  1. Nice Script, but can i get the server name as well like i can see the count of each OU that follow under the respective OU.


  2. If there are any duplicate names of OUs, the output will be inaccurate. A better way of doing this is to use Split-Path like this:

    Get-ADComputer -SearchBase “OU=servers,DC=example,DC=org” -Filter {Enabled -eq $true} -Properties CanonicalName | Group-Object {Split-Path $_.CanonicalName} | FT -Property Count, Name -AutoSize


    • Hi Craig,

      I no longer have access to an AD structure like I did when I posted this script, so I’m not sure if I can get back to you with an answer. I’ll have a look later today if I get time.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s