Here is a regular expression that can be used to match an Active Directory object's distinguished name to pull out the common name, organizational unit/container distinguished name, and/or the domain's distinguished name.

$regex_dn = '^CN=(?<cn>.+?)(?<!\\),(?<ou>(?:(?:OU|CN).+?(?<!\\),)+(?<dc>DC.+?))$'
$dn = "CN=John Doe,OU=My OU,DC=domain,DC=com"
$dn -match $regex_dn
$Matches

Output of $Matches showing the different parts that are pulled out.

Name              Value
----              -----
ou                OU=My OU,DC=domain,DC=com
cn                John Doe
dc                DC=domain,DC=com
0                 CN=John Doe,OU=My OU,DC=domain,DC=com

To reference a match:

$Matches['ou']

Output

OU=My OU,DC=domain,DC=com

Next Post Previous Post