Get an AD user’s manager

Interesting question on the forum about finding the manager for a given user in AD – assuming the Manager field is populated of course. If you’ve not worked with the AD cmdlets this is a good introduction to some of their quirks. This is how you get an AD user’s manager.

You need the manager property on the AD user account but that’s not one of the default properties that’s returned so you need to use the –Propertie parameter to ensure you get your data. Assuming you have a csv file with userids that looks like this

id userid
-- ------
1  DonBrown
2  DonFox
3  JamesBrown
4  JamesBlack

You can use this code

Import-Csv -Path .\names.csv |
foreach {
    $user = Get-ADUser -Identity $_.userid -Properties Manager
    $_ | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $user.Manager
    $_
 }

This returns the distinguished name of the manager

id userid     Manager                                           
-- ------     -------                                           
1  DonBrown   CN=HARRIS Fred,OU=UserAccounts,DC=Manticore,DC=org
2  DonFox     CN=HARRIS Fred,OU=UserAccounts,DC=Manticore,DC=org
3  JamesBrown CN=HARRIS Fred,OU=UserAccounts,DC=Manticore,DC=org
4  JamesBlack CN=HARRIS Fred,OU=UserAccounts,DC=Manticore,DC=org

if you prefer to have their name then you need an extra step

Import-Csv -Path .\names.csv |
 foreach {
    $user = Get-ADUser -Identity $_.userid -Properties Manager
    $manager = Get-ADUser -Identity $user.Manager
    
    $_ | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $manager.Name
    $_

 }

Which gives output like this

id userid     Manager    
-- ------     -------    
1  DonBrown   HARRIS Fred
2  DonFox     HARRIS Fred
3  JamesBrown HARRIS Fred
4  JamesBlack HARRIS Fred

If you need to output the data to a csv file then just add Export-Csv

Import-Csv -Path .\names.csv |
 foreach {
    $user = Get-ADUser -Identity $_.userid -Properties Manager
    $manager = Get-ADUser -Identity $user.Manager
    
    $_ | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $manager.Name
    $_

 } | Export-Csv -Path names2.csv –NoTypeInformation
This entry was posted in PowerShell and Active Directory. Bookmark the permalink.

1 Response to Get an AD user’s manager

  1. Pingback: PowerShell Schnipseljagd 49/17 | | PowerShell Usergroup Austria

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s