Search code examples
powershellactive-directory

Get all AD object name under specific OU


I would like to modify this PowerShell script below to export the OU members (Users and Computers) where the input will be like this:

$OUlist = @(
    domain.com/Site-A/OU1 
    domain.com/Site-A/OU2 
    domain.com/Site-B/OU1
    domain.com/Site-B/OU2 
    ... 
    domain.com/Site-Z/OU1 
    domain.com/Site-Z/OU99
)

$targetOUs = $OUList

$users = $targetOUs |ForEach-Object {
  Get-ADUser -Filter * -SearchBase $_.distinguishedName
  Get-ADComputer -Filter * -SearchBase $_.distinguishedName
} | Export-CSV "Result.csv" -NTI

Result.CSV content:

Name, Type
PC1, Computer
Person1, User
PC2, Computer
Person2, User

Solution

  • Since you have a list of CanonicalNames then you would need to query all OUs to properly get the OU's DistinguishedName to use as -SearchBase:

    $map = Get-ADOrganizationalUnit -Filter * -Properties canonicalName |
        Group-Object canonicalName -AsHashTable -AsString
    
    $targetOUs | ForEach-Object {
        # if this `CanonicalName` belongs to an existing OU
        if($map.ContainsKey($_)) {
            $queryParams = @{
                LDAPFilter  = '(objectClass=user)'
                SearchBase  = $map[$_].DistinguishedName
                SearchScope = 'OneLevel' # looking only for immediate objects
            }
    
            foreach($object in Get-ADObject @queryParams) {
                [pscustomobject]@{
                    Name     = $object.Name
                    Type     = $object.ObjectClass
                    SourceOU = $_
                }
            }
        }
    } | Export-CSV "Result.csv" -NTI
    

    Technically, computer objects are a subclass of the user class hence using the filter (objectClass=user) would find both, computers and users in a single query.