Last active
August 3, 2021 08:13
-
-
Save indented-automation/5078924d201db32cdf1d25883233d190 to your computer and use it in GitHub Desktop.
Split an AD DN into different parts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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