Skip to content

Instantly share code, notes, and snippets.

@kevinblumenfeld
Created September 2, 2017 05:10
Show Gist options
  • Save kevinblumenfeld/1c286aa5d56f81fb9ca9ae00656b36ad to your computer and use it in GitHub Desktop.
Save kevinblumenfeld/1c286aa5d56f81fb9ca9ae00656b36ad to your computer and use it in GitHub Desktop.
function ConvertTo-DistinguishedName {
[CmdletBinding()]
[OutputType([string])]
Param
(
# e.g. 'corp.ad.contoso.com/CORP/USERS/Person'
[Parameter(Mandatory = $true,
Position = 0)]
[ValidateNotNullOrEmpty()]
# must be at least a.b/w - no single character domain or missing path
[ValidatePattern('^.+\..+/.+$')]
$CanonicalName
)
$distinguishedNameParts = New-Object -TypeName System.Collections.ArrayList
# separate into domain part (a.b.c.d) and path+user part (/x/y/z/Person)
[string]$domain, [array]$remainder = $CanonicalName.Split('/')
#
# domain: 'a.b.c.d' -> 'DC=a,DC=b,DC=c,DC=d'
#
$null = $distinguishedNameParts.AddRange($domain.Split('.').ForEach( {"DC=$_"}))
$specialContainers = @('Users', 'Computers')
0..($remainder.Count - 1) | ForEach-Object {
#
# handle domain.com/{first} which might be
# OU={first}
# or a special container
# CN={first}
#
# and handle /Person at the end, which is CN=
# all other parts are OU=
#
$template = if ((($_ -eq 0) -and ($specialContainers -contains $remainder[$_])) -or ($_ -eq ($remainder.Count - 1))) {
'CN={0}'
}
else {
'OU={0}'
}
$null = $distinguishedNameParts.Insert(0, ($template -f $remainder[$_]))
}
$distinguishedNameParts -join ','
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment