Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active May 22, 2023 11:57
Show Gist options
  • Save scriptingstudio/85f03ba423214c638baac0da9b479274 to your computer and use it in GitHub Desktop.
Save scriptingstudio/85f03ba423214c638baac0da9b479274 to your computer and use it in GitHub Desktop.
Extract CN or directory path from DN
# Classic edition v1
function Split-DistinguishedName {
param (
[alias('dn')][string]$distinguishedName,
[alias('leaf')][switch]$cn,
[alias('parent')][switch]$ou,
[switch]$path
)
if (-not $distinguishedName) {return}
$dnpart = $distinguishedName -split '(,DC=)|(,OU=)|(,CN=)',2
if (-not $dnpart[1]) {return $distinguishedName}
$dpath = '{0}{1}' -f $dnpart[1].Substring(1),$dnpart[2]
if ($cn) {$dnpart[0] -replace 'CN='}
elseif ($path) {$dpath}
elseif ($ou) {
$dpath = ($dpath -split '(,DC=)|(,OU=)|(,CN=)',2)[0]
if ($dpath -match '^(CN|OU)=') {$dpath -replace 'CN=|OU='}
}
else {
$dnpart[0] -replace 'CN='
($dpath -split '(,DC=)|(,OU=)|(,CN=)',2)[0] -replace 'CN=|OU='
$dpath
}
} # END Split-DistinguishedName
# Regexp edition
function Split-DistinguishedName {
param (
[alias('dn')][string]$distinguishedName,
[alias('leaf')][switch]$cn,
[alias('parent')][switch]$ou,
[switch]$path
)
if (-not $distinguishedName) {return}
$rxOU = '^(CN=(?<CN>.*?(?=,))?),(?<OUName>(OU|CN)=.*?(?=,))'
$rxOU = '^(CN=(?<CN>.*?(?=,))?)(,OU|,CN)=(?<OUName>.*?(?=,))' # trims OU=|CN=
$rxPath = '^(CN=(?<CN>.*?(?=,))?),(?<Path>(OU=|CN=|DC=).+)'
if ($cn) {
if ($distinguishedName -match $rxPath) {$matches['CN']}
}
elseif ($path) {
if ($distinguishedName -match $rxPath) {$matches['Path']}
}
elseif ($ou) {
if ($distinguishedName -match $rxOU) {$matches['OUName']}
}
else {
if ($distinguishedName -match $rxPath) {
$c,$p = $matches['CN','Path']
$n = if ($distinguishedName -match $rxOU) {$matches['OUName']} #else {}
$c,$n,$p
}
}
} # END Split-DistinguishedName
# Classic edition v2
function Split-DistinguishedName {
param (
[alias('dn')][string]$distinguishedName,
[alias('leaf')][switch]$cn,
[alias('parent')][switch]$ou,
[switch]$path
)
if (-not $distinguishedName) {return}
$parts = $distinguishedName -split '(CN=)|(OU=)|(DC=)'
$dnparts = for ($i=2; $i -lt $parts.count; $i+=2) {
'{0}{1}' -f $parts[$i-1], $parts[$i].TrimEnd(',')
}
if ($cn) {
if ($dnparts[0] -match '^CN') {$dnparts[0] -replace 'CN='}
} elseif ($path) {
if ($dnparts[1]) {$dnparts[1..($dnparts.count-1)] -join ','}
} elseif ($ou) {
if ($dnparts[1] -match '^(CN|OU)=') {$dnparts[1] -replace 'CN=|OU='}
} else {$dnparts}
} # END Split-DistinguishedName
split-distinguishedName 'CN=Berge, Karen,OU=fkr,CN=admin,DC=corp,DC=Fabrikam,DC=COM'
Berge, Karen
split-distinguishedName 'CN=Berge, Karen,OU=fkr,CN=admin,DC=corp,DC=Fabrikam,DC=COM' -path
OU=fkr,CN=admin,DC=corp,DC=Fabrikam,DC=COM
split-distinguishedName 'CN=Berge, Karen,CN=admin,DC=corp,DC=Fabrikam,DC=COM' -ou
admin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment