How to Split DistinguishedName?

后端 未结 4 760
孤独总比滥情好
孤独总比滥情好 2020-12-21 11:14

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=         


        
相关标签:
4条回答
  • 2020-12-21 11:19

    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.

    0 讨论(0)
  • 2020-12-21 11:24

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

    0 讨论(0)
  • 2020-12-21 11:26

    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 "^,"
    
    0 讨论(0)
  • 2020-12-21 11:42

    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
    
    0 讨论(0)
提交回复
热议问题