header image

Not the comma!

Posted by: | February 6, 2016 Comments Off on Not the comma! |

There is a habit among some AD administrators to create their users so that the name is surname, firstname   – Note the comma between the two names. As an example the name would be

Brown, Bill

instaead of

Bill Brown


If you’re just using the GUI tools it doesn’t matter too much and has the arguable advantage of ordering the users by surname. But when it comes to scripting against AD this practice is a complete pain.

Compare these 2 distinguished names

CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org

CN=Dave Green,OU=Testing,DC=Manticore,DC=org


Notice the extra comma in the first one. That destroys any chance of splitting the distinguished name on commas – which are the element separators in distinguished names.

You have to escape the comma in the name with a \


The GUI tools (at least in Windows server 2012 R2) do this for you so the distinguished name looks like this:

CN=Brown\, Bill,OU=Testing,DC=Manticore,DC=org


If you want to get a user by distinguished name this will work:

Get-ADUser -Identity ‘CN=Dave Green,OU=Testing,DC=Manticore,DC=org’


This won’t

Get-ADUser -Identity ‘CN=Brown, Bill,OU=Testing,DC=Manticore,DC=org’


You have to use the escaped version:

Get-ADUser -Identity ‘CN=Brown\, Bill,OU=Testing,DC=Manticore,DC=org’


In my last post I showed how to extract the users OU from the distinguished name

Get-ADUser -Filter * -Properties DisplayName |
select Name, DisplayName, UserPrincipalname, @{N= "Organanisational Unit" ;
E = {($_.DistinguishedName -split ‘,’, 2)[1]}}


That code breaks down if you have a comma in the name and you get


for the OU instead of



Its probably possible to do some regex voodoo to deal with this but as the Universe doesn’t have enough life left in it for me to figure this out I’ll resort to a brute force approach:

Get-ADUser -Filter * -Properties DisplayName |
foreach {
$ouf = ($_.DistinguishedName -split ‘,’, 2)[1]
if (-not ($ouf.StartsWith(‘OU’) -or $ouf.StartsWith(‘CN’) )){
  $ou = ($ouf -split ‘,’, 2)[1]
else {
  $ou = $ouf
$psitem | select Name, DisplayName, UserPrincipalname, @{N= "Organanizational Unit" ;E = {$ou}}


Do the inital split as previously but then test the reasults to see if it starts with CN= or OU=. If it doesn’t then split again.

Its not elegant but it works.

It sa lot easier if you don’t use the comma in the first place Smile

under: PowerShell and Active Directory

Comments are closed.