PoshCode Archive  Artifact [36426b8a5e]

Artifact 36426b8a5eb96e10bfc0a1b466eed24baf73087d0c1c487c2a70c7342325de96:

  • File ConvertTo-DN.ps1 — part of check-in [41623f063d] at 2018-06-10 13:57: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: 1897)

# 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: 5611
# x-archived: 2014-12-09T12:02:06
# x-published: 2014-11-24T18:27:00
#
# spelling errors fixed :)
#
#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=","");continue}
            "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue}
            "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue}
        }
    } 
    $canoincal = $dc.Substring(0,$dc.length - 1)
    for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]}
    $canoincal += $cn.ToString().replace('~',',')
    return $canoincal
}

function ConvertFrom-Canonical 
{
param([string]$canoincal=(throw '$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
}