How to Split DistinguishedName?

2019-01-28 17:47发布

问题:

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

回答1:

I decided to turn my comment into an answer:

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

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).



回答2:

You can remove the first element with a replacement like this:

$DNList -replace '^.*?,(..=.*)$', '$1'

^.*?, is the shortest match from the beginning of the string to a comma.
(..=.*)$ matches the rest of the string (starting with two characters after the comma followed by a = character) and groups them, so that the match can be referenced in the replacement as $1.



回答3:

You have 7 items per user, comma separated and you want rid of the first one.

So, split each item in the array using commas as the delimiter, return matches 1-6 (0 being the first item that you want to skip), then join with commas again e.g.

$DNList = $DNList|foreach{($_ -split ',')[1..6] -join ','}

If you then enter $DNList it returns

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


回答4:

Similar to Grahams answer but removed the hardcoded array values so it will just remove the CN portion without worrying how long the DN is.

$DNList | ForEach-Object{($_ -split "," | Select-Object -Skip 1) -join ","}

Ansgar most likely has a good reason but you can just use regex to remove every before the first comma

$DNList -replace "^.*?,"

Update based on briantist

To maintain a different answer but one that works this regex can still have issues but I doubt these characters will appear in a username

$DNList -replace "^.*?,(?=OU=)"

Regex uses a look ahead to be sure the , is followed by OU=

Similarly you could do this

($DNList | ForEach-Object{($_ -split "(,OU=)" | Select-Object -Skip 1) -join ""}) -replace "^,"