Convert a Domain Name to a Distinguished Name in PowerShell

Here is a small PowerShell snippet to easily convert a Domain Name (e.g. corp.bmdlab.com) to a distinguished name (DC=corp,DC=bmdlab,DC=com):

[String]$Domain = 'corp.bmdlab.com'

# Create an empty string that the DN will be stored in
[String]$DN = ''

# Assemble the DN by splitting the DC and then looping to concatenate the new
$Domain.Split('.') | % { $DN = "DC=$($_),$DN" }

# An extra . will be left on the end of DN, so strip it off
$DN = $DN.SubString(0,$DN.Length-1)

An even easier way would be to use the Replace method on a string object:

[String]$Domain = 'corp.bmdlab.com'

# Assemble the DN by replacing 
$DN = 'CN=' + $Domain.Replace('.',',CN=')

That is all!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s