Get AD OU Distingushied Name quickly


Function Get-OUDistinguishedName{

    <#
    .SYNOPSIS
    Returns DN name for every OU that matches OUName parameter.

    .DESCRIPTION
    Returns DN name for every OU that matches OUName parameter.

    .EXAMPLE
    PS> Get-OUDistinguishedName -OUName OU_2
    OU=OU_2,DC=test,DC=local

    #>

    Param(
        [string[]]$OUName,
        [switch]$Recurse,
        [string]$DomainController,
        [psobject]$Credential
    )

    BEGIN{}
    PROCESS{

        foreach($OU in $OUName){

            IF($DomainController){
                IF($Recurse){
                    $OU1 = (Get-ADOrganizationalUnit -Server $DomainController -Cred $Credential -Filter {name -like $OU}).DistinguishedName
                    $OU1 | %{ (Get-ADOrganizationalUnit -Server $DomainController -Cred $Credential -LDAPFilter '(name=*)' -SearchBase $_ -SearchScope Subtree).DistinguishedName }
                    }ELSE{
                    (Get-ADOrganizationalUnit -Server $DomainController -Cred $Credential -Filter {name -like $OU}).DistinguishedName
                    }

            }ELSE{
                IF($Recurse){
                    $OU1 = (Get-ADOrganizationalUnit -Filter {name -like $OU}).DistinguishedName
                    $OU1 | %{ (Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $_ -SearchScope Subtree).DistinguishedName }
                    }ELSE{
                    (Get-ADOrganizationalUnit -Filter {name -like $OU}).DistinguishedName
                    }
            }
        }        

    }
    END{}

}

Leave a Reply

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