header image

Get an AD user’s manager

Posted by: | November 27, 2017 Comments Off on 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
under: PowerShell and Active Directory

Comments are closed.

Categories