Count Objects in AD OUs – Powershell

A recent request we had was to count the number of objects in each OU in AD, so we could identify which ones were not being used any more. To achieve this we used a PowerShell script, and exported to a csv file.

I have seen a number of scripts that will count the number of Users, Computers or Groups in an OU, but we wanted to combine these, so we can see both object counts in one report.

Get-ADOrganizationalUnit -filter * -property Description |
foreach {
  $u=Get-ADuser -filter * -searchbase $_.distinguishedname -searchscope Onelevel 
  $totalu=($u | measure-object).count
  $Enabledu=($u | where {$_.Enabled} | Measure-Object).count
  $Disabledu=$totalu-$Enabledu
  $c=Get-ADcomputer -filter * -searchbase $_.distinguishedname -searchscope Onelevel
  $totalc=($c | measure-object).count
  $Enabledc=($c | where {$_.Enabled} | Measure-Object).count
  $Disabledc=$totalc-$Enabledc
  $g=Get-ADGroup -Filter * -searchbase $_.distinguishedname -searchscope Onelevel
  $Totalg=($g | measure-object).count
  New-Object psobject -Property @{
    Name=$_.Name;
    OU=$_.Distinguishedname;
    Description=$_.Description;
    TotalUsers=$Totalu;
    EnabledUser=$Enabledu;
    DisabledUser=$Disabledu
    TotalComputers=$Totalc;
    EnabledComp=$Enabledc;
    DisabledComp=$Disabledc
    TotalGroups=$Totalg
    }
} |

Export-csv c:\temp\OUsObjects.csv -NoTypeInformation

This gives you a great output of both the Users, Computers or Groups in each OU in your domain, including both Enabled and Disabled counts.

Leave a Reply

Your email address will not be published. Required fields are marked *