PoshCode Logo PowerShell Code Repository

ConvertTo-DN (modification of post by view diff)
View followups from glnsize | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/511"></script>download | new post

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 :)

  1. #Author:        Glenn Sizemore glnsize@get-admin.com
  2. #
  3. #Purpose:       Convert a DN to a conicalname, and back again.
  4. #
  5. #Example:       PS > ConvertFrom-Canonical 'get-admin.local/test/test1/Sizemore, Glenn E'
  6. #               CN=Sizemore\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local
  7. #               PS > ConvertFrom-DN 'CN=Sizemore\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local'
  8. #               get-admin.local/test/test1/Sizemore, Glenn E
  9.  
  10.  
  11. function ConvertFrom-DN
  12. {
  13. param([string]$DN=(Throw '$DN is required!'))
  14.     foreach ( $item in ($DN.replace('\,','~').split(",")))
  15.     {
  16.         switch -regex ($item.TrimStart().Substring(0,3))
  17.         {
  18.             "CN=" {$CN = '/' + $item.replace("CN=","");continue}
  19.             "OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue}
  20.             "DC=" {$DC += $item.replace("DC=","");$DC += '.';continue}
  21.         }
  22.     }
  23.     $canoincal = $dc.Substring(0,$dc.length - 1)
  24.     for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]}
  25.     $canoincal += $cn.ToString().replace('~',',')
  26.     return $canoincal
  27. }
  28.  
  29. function ConvertFrom-Canonical
  30. {
  31. param([string]$canoincal=(trow '$Canonical is required!'))
  32.     $obj = $canoincal.Replace(',','\,').Split('/')
  33.     [string]$DN = "CN=" + $obj[$obj.count - 1]
  34.     for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]}
  35.     $obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_}
  36.     return $dn
  37. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me