powershellactive-directory

Using Get-ADOrganizationalUnit to get OU recursively?


I couldn't make this piece of code work for me to return all subtree OU and its structure below.

Because when I execute this snippet, it only returns the top-level OU, not including the Subtree OU underneath it?

This is the script:

$AllOUs = @(
    'Production Global'
    'Testing'
) | ForEach-Object {
    If ($ou = Get-ADOrganizationalUnit -SearchScope Subtree -Filter "name -eq '$($_)'") {
        $ou.DistinguishedName
    }
    Else {
        Throw "OU '$($_)' not found!"
    }
}

This is the incomplete result:

OU=Production Global,DC=domain,DC=com
OU=Testing,DC=domain,DC=com

Below is the structure of the OU in my current AD:

OU=Production Global,DC=domain,DC=com
    OU=Azure,OU=Production Global,DC=domain,DC=com
    OU=AWS,OU=Production Global,DC=domain,DC=com
    OU=GCP,OU=Production Global,DC=domain,DC=com

OU=Testing,DC=domain,DC=com
    OU=IT-Developer,OU=Testing,DC=domain,DC=com
        OU=Team1,OU=IT-Developer,OU=Testing,DC=domain,DC=com
        OU=Team2,OU=IT-Developer,OU=Testing,DC=domain,DC=com
    OU=UAT,OU=Testing,DC=domain,DC=com
        OU=CustomerA,OU=UAT,OU=Testing,DC=domain,DC=com
        OU=CustomerB,OU=UAT,OU=Testing,DC=domain,DC=com

What can be done to return that result as above?

I also got this error below:

Get-ADOrganizationalUnit : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'SearchBase'. Specified method is not supported.
At line:20 char:50
+ ... rganizationalUnit -Filter * -SearchBase $ou.DistinguishedName -Search ...
+                                             ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADOrganizationalUnit], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit

Solution

  • Below is correct script instead of filter, use searchbase

    $AllOUs = @(
        'Production Global'
        'Testing'
    ) | ForEach-Object {
    
        $o = Get-ADOrganizationalUnit -Filter "name -eq '$($_)'"
        If ($ou = Get-ADOrganizationalUnit -SearchScope Subtree -Searchbase $o) {
            $ou.DistinguishedName
        }
        Else {
            Throw "OU '$($_)' not found!"
        }
    }