How to Split DistinguishedName?

Mark Smith Marcus T picture Mark Smith Marcus T · May 1, 2015 · Viewed 22.9k times · Source

I have a list of folks and their DN from AD (I do not have direct access to that AD). Their DNs are in format:

$DNList = 'CN=Bob Dylan,OU=Users,OU=Dept,OU=Agency,OU=NorthState,DC=myworld,DC=com',
          'CN=Ray Charles,OU=Contractors,OU=Dept,OU=Agency,OU=NorthState,DC=myworld,DC=com',
          'CN=Martin Sheen,OU=Users,OU=Dept,OU=Agency,OU=WaySouth,DC=myworld,DC=com'

I'd like to make $DNList return the following:

OU=Users,OU=Dept,OU=Agency,OU=NorthState,DC=myworld,DC=com
OU=Contractors,OU=Dept,OU=Agency,OU=NorthState,DC=myworld,DC=com
OU=Users,OU=Dept,OU=Agency,OU=WaySouth,DC=myworld,DC=com

Answer

briantist picture briantist · May 1, 2015

I decided to turn my comment into an answer:

$DNList | ForEach-Object {
    $_ -replace '^.+?(?<!\\),',''
}

Regular expression visualization

Debuggex Demo

This will correctly handle escaped commas that are part of the first component.

We do a non-greedy match for one or more characters at the beginning of the string, then look for a comma that is not preceded by a backslash (so that the dot will match the backslash and comma combination and keep going).