How to Split DistinguishedName?

[亡魂溺海] 提交于 2019-11-29 16:00:39

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

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.

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 

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 "^," 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!