In .Net, substitutions in regular expression replacement patterns are preceeded with the dollar symbol. Powershell also uses the dollar sign for variables. And, since Powershell attempts to expand variable when they are in double quoted strings, when passing a replacement pattern to a regular expression based operator or function, you must either use single quotes or escape the dollar symbol. Otherwise, Powershell will attempt the expand the regular expression substitution as if it were a powershell variable.
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