Display result as samaccountname instead of common name?

Hello PowerShell.org,

Just made the jump from Help Desk to Infrastructure and I am suddenly wish I used PowerShell for more than a glorified command prompt before now. Hopefully my first question is a really easy one for the seasoned pros:

Get-ADUser -Identity <SAMAcountname. -Property Manager gives the manager in the common name format… How can I get this result as SAMAccountName (FirstInitialLastName)?

The end goal here is to enter the SAMAccountName as an extensionAttribute, which will translate to a Custom Attribute in Exchange, allowing me to create a dynamic distribution group for a manager and all of their direct reports. I figure this is the easiest approach but if I am wrong, call me on it, I’m here to learn. Thanks in advance for your time!

Cheers,

Harrison

  • Get the user’s manager using Get-ADUser
  • Then use the distinguished name to get the identity of the Manager
$User = Get-ADUser -Identity User -Properties Manager
$Manager = ($User.Manager  -split ',')[0].TrimStart('CN=')
$Manager

You can get the manager’s SamAccountName in a one-liner.

Get-ADUser -Identity user -Properties Manager |Select-Object -ExpandProperty Manager |Get-ADUser |Select-Object SamAccountName

pwshliquori

My bad, I forgot the pipelinme for a moment !

I suggest the oneliner…

Well, you could have done this as well.

(Get-ADUser (Get-ADUser -Identity $env:USERNAME -Properties Manager).Manager).SamAccountName

This one liner works perfect! I combined it with a Get-ADUser using a foreach:

Import-Module ‘ActiveDirectory’
get-aduser -filter {employeeType -eq ‘Active’} -searchbase “OU=container,OU=container,DC=domain,DC=domain,DC=com” | select SAMAccountname |

foreach {
Get-ADUser -Identity $_.SAMAccountName -Properties Manager |Select-Object -ExpandProperty Manager |Get-ADUser |Select-Object SamAccountName
}

This will only show me the managers of the users (not users themselves). I assume I will need to add a | ft SAMAccountName,Manager somewhere but I am unsure of how to work that in with the right syntax…

I feel pretty lame bringing basics like this up but I am spinning my wheels at this point… My copy of “Learn Windows PowerShell in a Month of Lunches, Third Edition” is in the mail, I swear!