Powershell: one liner to extract CN from DN (DistinguishedName)

10 Oct

I know there are various solutions out there, I tried some of them but couldn’t get them going. I am not too much an expert in regular expression (trying to understand negative lookback, etc) at the moment, so this is a rather brute force (not so elegant) solution that worked for me.

Note below: I am breaking up the code with “_” for readability sake, the codes should be in a single line.

To start with, I need to get the ManagedBy properties of a list of groups. As you know when you do that, you get the DN of the managers. This is the first code I used:

get-content .\file.txt | get-adgroup -properties ManagedBy | _
 % {$_.Name + "`t" + $_.ManagedBy } | _
 Out-file .\file-out.txt -append

The output looks like this:

group1     CN=Wong\, Kelvin,OU=Users,DC=contoso,DC=com
group2     CN=Wong\, Kelvin,OU=Users,DC=contoso,DC=com

My upgraded version which extracts the CN looks like this

get-content .\file.txt | get-adgroup -properties ManagedBy | _
 % {$_.Name + "`t" + _
(($_.ManagedBy -replace "\\,","~").split(",")[0].substring(3) _
 -replace "~",",") } | _
 Out-file .\file-out.txt -append

The output now looks like this:

group1     Wong, Kelvin
group2     Wong, Kelvin

The magic, of course, occurs in this one-liner:

(($_.ManagedBy -replace "\\,","~").split(",")[0].substring(3) _ 
-replace "~",",")

Let’s have a look at how this works:

$_.ManagedBy -replace “\\,”,”~” simply replaces “\,” in “CN=Wong\, Kelvin,OU=xxx” with “CN=Wong~ Kelvin,OU=xxx”. This is important as “,” is used as a split delimiter in the next command. Without this replacement, the CN’s first and last name will be split also.

Next,  $_.ManagedBy -replace “\\,”,”~”).split(“,”)[0] splits the DN using “,” as delimiter and [0] references the first element in the array, which is “CN=Wong~ Kelvin”

substring(3) then extracts the name from the 3rd character onwards, stripping away “CN=”

Lastly, another replace is apply -replace “~”,”,” to restore the “,” in the name.


Posted by on October 10, 2012 in powershell, Scripts



3 responses to “Powershell: one liner to extract CN from DN (DistinguishedName)

  1. Adam

    January 28, 2015 at 9:23 pm

    This worked – thank you!

  2. Dave

    January 11, 2017 at 6:23 am

    Thank You

  3. Ken

    July 20, 2019 at 3:15 am

    Thank you for this. Many references from my search and it helped me a lot.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: