Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active August 3, 2021 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indented-automation/5078924d201db32cdf1d25883233d190 to your computer and use it in GitHub Desktop.
Save indented-automation/5078924d201db32cdf1d25883233d190 to your computer and use it in GitHub Desktop.
Split an AD DN into different parts
function Split-DistinguishedName {
<#
.SYNOPSIS
Split a distinguishedName into named pieces.
.DESCRIPTION
Split a distinguishedName into Name, ParentDN, ParentName, and DomainComponent.
.EXAMPLE
Split-DistinguishedName 'OU=somewhere,DC=domain,DC=com'
Returns an object containing each of the elements of the DN.
.EXAMPLE
'CN=last\, first,OU=somewhere,DC=domain,DC=com' | Split-DistinguishedName -Property ParentDN
Returns the parent distinguishedName, OU=somewhere,DC=domain,DC=com
#>
[CmdletBinding(DefaultParameterSetName = 'ToObject')]
[Alias('Split-DN')]
param (
[Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('DN')]
[string]$DistinguishedName,
[Parameter(Mandatory, ParameterSetName = 'Leaf')]
[switch]$Leaf,
[Parameter(Mandatory, ParameterSetName = 'Parent')]
[switch]$Parent,
[Parameter(Mandatory, ParameterSetName = 'GetProperty')]
[ValidateSet('Name', 'ParentDN', 'ParentName', 'DomainComponent')]
[string]$Property
)
begin {
if ($Leaf) {
$Property = 'Name'
}
if ($Parent) {
$Property = 'ParentDN'
}
}
process {
if ($DistinguishedName -match '^(?:CN|OU|DC)=(?<Name>.*?),(?<ParentDN>(?:CN|OU|DC)=(?<ParentName>.*?(?=,(?:CN|OU|DC))).*?(?<DomainComponent>DC=.*))') {
if ($Property) {
$matches[$Property]
} else {
$matches.Remove(0)
[PSCustomObject]$matches
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment