PoshCode Archive  Artifact [30791bad1c]

Artifact 30791bad1c1197279d88f0de1ba7234f63d25a35a9a2a1b28bba74b488339e41:

  • File ConvertTo-DN.ps1 — part of check-in [559ded4318] at 2018-06-10 14:15:57 on branch trunk — A couple functions I use to convert DN to Canonical, and canonical to DN. I find them handy for adhoc AD tasks… I saw someone ask about it on #powershell and figured I would share :) (user: Glenn Sizemore glnsize size: 2063)

# encoding: ascii
# api: powershell
# title: ConvertTo-DN
# description: A couple functions I use to convert DN to Canonical, and canonical to DN. I find them handy for adhoc AD tasks… I saw someone ask about it on #powershell and figured I would share :)  
# version: 0.1
# type: function
# author: Glenn Sizemore glnsize
# license: CC0
# function: ConvertFrom-DN
# x-poshcode-id: 6445
# x-archived: 2016-09-16T11:48:09
# x-published: 2016-07-13T03:46:00
#
# Minor modifications to handle no OU present and multiple CN case e.g. CN=MyComputer,CN=Computers,DC=MyDomain,DC=Local
#
#Author:    	Glenn Sizemore glnsize@get-admin.com
#
#Purpose:	Convert a DN to a Canonical name, and back again.
#
#Example:	PS > ConvertFrom-Canonical 'get-admin.local/test/test1/Sizemore, Glenn E'
#		CN=Sizemore\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local
#	 	PS > ConvertFrom-DN 'CN=Sizemore\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local'
#		get-admin.local/test/test1/Sizemore, Glenn E


function ConvertFrom-DN 
{
param([string]$DN=(Throw '$DN is required!'))
    foreach ( $item in ($DN.replace('\,','~').split(",")))
    {
        switch -regex ($item.TrimStart().Substring(0,3))
        {
            "CN=" {$cn += ,$item.replace("CN=","");$cn += '/';continue}
            "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue}
            "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue}
        }
    } 
    $canoincal = $dc.Substring(0,$dc.length - 1)
    if ($ou -ne $null) { for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]} }
    for ($i = $cn.count-1;$i -ge 0;$i -- ){$canoincal += $cn[$i].ToString().replace('~',',')}
    return $canoincal
}

function ConvertFrom-Canonical 
{
param([string]$canoincal=(trow '$Canonical is required!'))
    $obj = $canoincal.Replace(',','\,').Split('/')
    [string]$DN = "CN=" + $obj[$obj.count - 1]
    for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]}
    $obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_}
    return $dn
}