PowerShell for Windows Admins

Feb 6 2016   6:11AM GMT

Not the comma!

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Active Directory
Powershell

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

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

for the OU instead of

OU=Testing,DC=Manticore,DC=org

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 initial split as previously but then test the results to see if it starts with CN= or OU=. If it doesn’t then split again.

Its not elegant but it works.

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: