In this short article, I would like to share the PowerShell script for getting computer objects from parent Organizational Units (OUs).
Organizational Unit (OU) is a container in the Active Directory domain that can contain different objects from the same AD domain: other containers, groups, user and computer accounts.
Get computer objects
Recently I was asked to prepare a report in Excel and count objects in each OU. To do that I used commands from ActiveDirectory module and edit results in Excel with PivotChart option.

Basically, this script is based only on two Active Directory commands:
- Get-ADOrganizationalUnit
- Get-ADComputer
First, we have to get all OUs using Subtree in -SearchScope parameter:
(Get-ADOrganizationalUnit -Filter * -SearchBase 'OU=Servers,DC=powershellbros,DC=com' -SearchScope Subtree) | select DistinguishedName
Next, we have to loop each OU using Get-ADComputer command with -SearchBase parameter to get computer objects.
Final script:
$OUs = (Get-ADOrganizationalUnit -Filter * -SearchBase 'OU=Servers,DC=powershellbros,DC=com' -SearchScope Subtree) | select DistinguishedName $Results = @() $Results = Foreach ($item in $OUs){ $ComputerObjects = Get-ADComputer -Filter * -SearchBase $item.DistinguishedName -SearchScope OneLevel If($ComputerObjects){ Foreach ($i in $ComputersObjects){ $Object = @{} | Select 'OU Distinguishedname', 'Computername' $Object.Computername = $i.dnshostname $Object.'OU Distinguishedname' = $item.DistinguishedName $Object } } } $Results | Export-Csv $env:userprofile\desktop\OUS.csv -Force -NoTypeInformation
Results:
