Forked from wolffberg/ConvertTo-DistinguishedName.ps1
Created
February 11, 2021 05:27
-
-
Save FracVX/bdd90595a4ef453f63617f86a6b77134 to your computer and use it in GitHub Desktop.
Function to check and convert CanonicalName to DestinguishedName
This file contains hidden or 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 ConvertTo-DistinguishedName{ | |
[CmdletBinding()] | |
Param( | |
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] | |
$CanonicalName | |
) | |
Begin{ | |
# StringBuilders used to build DestinguishedName and LDAP query | |
$dn = [System.Text.StringBuilder]::new() | |
$ldapQuery = [System.Text.StringBuilder]::new() | |
# Static variables | |
$objectTypes = 'OU','CN','DC' | |
# StrictMode bypass | |
$r = '' | |
} | |
Process{ | |
[void]$dn.Clear() | |
$arrParts = $CanonicalName.Trim('/') -Split '(?<!\\)/' | |
foreach($part in $arrParts){ | |
if(!$part){ | |
Write-Error "CanonicalName '$CanonicalName' incorrect" | |
} | |
} | |
# Adding DC | |
[void]$dn.Append($($arrParts[0].Split('.')|ForEach-Object {[string]$r += "DC=$_,"} -End {$r.Trim(','); $r = $null})) | |
if($arrParts.Count -gt 1){ | |
# Check if leaf object is located within one or multiple OUs | |
if($arrParts.Count -gt 2){ | |
# Adding OUs | |
foreach($part in $arrParts[1..($arrParts.Count -2)]){ | |
[void]$dn.Insert(0, "OU=$part,") | |
} | |
} | |
# Adding leaf | |
[void]$dn.Insert(0, "=$($arrParts[$arrParts.Count - 1]),") | |
foreach($o in $objectTypes){ | |
[void]$ldapQuery.Clear() | |
[void]$ldapQuery.Append("LDAP://$o") | |
[void]$ldapQuery.Append($dn) | |
try{ | |
$works = [adsi]::Exists($ldapQuery) | |
} | |
catch{ | |
if($_.Exception.HResult -ne -2146233087){ | |
throw $_.Exception | |
} | |
} | |
if($works){ | |
break | |
} | |
} | |
} | |
if(!$works){ | |
Write-Error "The object '$CanonicalName' could not be found" | |
} | |
else{ | |
Write-Output "$o$($dn.ToString())" | |
} | |
# Cleanup | |
$works = $false | |
} | |
End{ | |
# Nullify StringBuilders | |
$dn = $null | |
$ldapQuery = $null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment