How can I use Regex to pull just the CN from a Distinguished Name with PowerShell

后端 未结 6 1828
礼貌的吻别
礼貌的吻别 2020-12-11 21:04

I have a bunch of strings that are DN\'s of groups from AD. I need to pull out the Common Name. An example string is \"CN=Group Name I Want,OU=Group Container,DC=corp,DC=tes

6条回答
  •  旧巷少年郎
    2020-12-11 21:55

    An even shorter variation on jon Z's answer:

    $s = "CN=Group Name I Want,OU=Group Container,DC=corp,DC=test,DC=local"
    $s = $s -replace '^CN=|,.*$'
    

    The ^ and $ are the string beginning and end anchors. The | is an "or".

    The matches are the CN= at the beginning of the line or a string that starts with a comma and goes to the end of the line (i.e. everything after the CN). The replace is replacing with nothing, so you're discarding all the matches and leaving just the CN itself.

    That obviously does not work if you have a comma in your CN (ugh).

    Assuming such a comma is followed by a space, this will work and be fine for the previous examples (\S - non whitespace char):

    $s = $s -replace '^CN=|,\S.*$'
    

    I tested to see if jon Z's or this variation was faster to execute. With 1,470,000 DNs, the first took 36.87s to execute and the one here took 34.75. Not really a lot in it.

    That was reading the DNs out of a file. Bizarrely, "slurping" the file into an array and executing over that took both regexes a minute longer. The PC was not memory-bound - the file was only 100MB. Can't be bothered getting to the bottom of that one right now!

提交回复
热议问题