PowerShell Validate Distinguished Name

1 minute read

Any administrator or engineer who ever had to deal with an LDAP database will know this by heart but anyhow a DistinguishedName(DN) is a string that uniquely identifies an entry in the Directory Database, in the Microsoft implementation Active Directory.

Note: I love LDAP Wiki explanation on the subject.

In my Get users reporting to manager I explored how we can leverage AD OID to get a full report of use users, direct and indirect, reporting to a specific manager and the main argument to our LDAP query was the user’s DN which raised the question

How can I validate an input string is a valid object DN?

Finding an answer was not super easy as there are lot of variables to take into account but finally I’ve been able to come up with the Test-IsValidDN function which you can find below

function Test-IsValidDN
            Cmdlet will check if the input string is a valid distinguishedname.

            Cmdlet will check if the input string is a valid distinguishedname.

            Cmdlet is intended as a dignostic tool for input validation

        .PARAMETER ObjectDN
            A string representing the object distinguishedname.

            PS C:\> Test-IsValidDN -ObjectDN 'Value1'

            Additional information about the function.

        [Parameter(Mandatory = $true)]
        [Alias('DN', 'DistinguishedName')]

    # Define DN Regex
    [regex]$distinguishedNameRegex = '^(?:(?<cn>CN=(?<name>(?:[^,]|\,)*)),)?(?:(?<path>(?:(?:CN|OU)=(?:[^,]|\,)+,?)+),)?(?<domain>(?:DC=(?:[^,]|\,)+,?)+)$'

    return $ObjectDN -match $distinguishedNameRegex

# Test if string is a valid DN
Test-IsValidDN -ObjectDn 'OU=Sales+CN=J. Smith,DC=example,DC=net'

# Output

Important: Function has been written with Active Directory DN format in mind, which does not strictly adhere to LDAP standards, so function will not match DNs like UID=jsmith,DC=example,DC=net or,DC=example,DC=com which are perfectly valid DNs.

As usual you can find code function in my PowerShell Functions Repository or in my IT-Toolbox module.

Leave a comment