title: Get the canonical name instead of the distinguished name in powershell?
body: <p>I would like to get the Canonical name in my report instead of the distinguished name.  That way I can sort on the OU which makes it easier to present.</p>
  
  <p>To have <code>domain.com/users/someuser/username</code> easily sorted.</p>
  
  <p>Here is my code</p>
  
  <pre><code>Import-Module activeDirectory
  
  $output = Read-Host "'Y' for output to file or any key for output in GUI table view" -foreground Cyan
  $fqdn = Read-Host "Enter FQDN domain"
  $cred = Get-Credential
  
  Write-Host "Contacting $fqdn domain..." -ForegroundColor Yellow
  
  $domain = (get-addomain $fqdn -Credential $cred | select distinguishedName, pdcEmulator, DNSroot, DomainControllersContainer)
  
  Write-Host "Completed. Enumerating OUs.." -ForegroundColor Yellow
  
  $OUlist = @(Get-ADOrganizationalUnit -filter * -Credential $cred -SearchBase $domain.distinguishedName -SearchScope Subtree -Server $domain.DNSroot)
  Write-Host "Completed. Counting users..." -ForegroundColor Yellow
  
  for ($i = 1; $i -le $oulist.Count; $i++)
      { write-progress -Activity "Collecting OUs" -Status "Finding OUs $i" -PercentComplete ($i/$OUlist.count * 100) }
  $newlist = @{ }
  
  
  
  foreach ($_objectitem in $OUlist)
  {
      $getUser = Get-ADuser -Filter * -Credential $cred -SearchBase $_objectItem.DistinguishedName -SearchScope OneLevel -Server $domain.pdcEmulator | measure | select Count
      for ($i = 1; $i -le $getUser.Count; $i++)
      { write-progress -Activity "Counting users" -Status "Finding users $i in $_objectitem" -PercentComplete ($i/$getUser.count * 100) }
  
      $newlist.add($_objectItem.DistinguishedName, $getUser.Count)
  
  }
  
  if ($output -eq "Y")
  {
      $newlist | ft -AutoSize | Out-File .\OUuserCount.txt
  
  
      Write-Host "All done!" -ForegroundColor yellow
  }
  else
  {
      $newList | Out-GridView
  }
  </code></pre>