Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Split an AD DN into different parts
function Split-DistinguishedName {
Split a distinguishedName into named pieces.
Split a distinguishedName into Name, ParentDN, ParentName, and DomainComponent.
Split-DistinguishedName 'OU=somewhere,DC=domain,DC=com'
Returns an object containing each of the elements of the DN.
'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')]
param (
[Parameter(Mandatory, Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Parameter(Mandatory, ParameterSetName = 'Leaf')]
[Parameter(Mandatory, ParameterSetName = 'Parent')]
[Parameter(Mandatory, ParameterSetName = 'GetProperty')]
[ValidateSet('Name', 'ParentDN', 'ParentName', 'DomainComponent')]
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) {
} else {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment