Author Posts

November 27, 2017 at 4:20 pm

Hi

I have a Csv file in below format.

some-id userid
1 test1
2 test2
3 test3
4 test4
5 test5

I want to select "userid" column and i need to find out the manager for each user, and append csv in 3rd column with user's manager name. How to achieve this task. Please advise

Thanks in advace
Raghav

November 27, 2017 at 4:34 pm

what code have you written so far?

November 27, 2017 at 5:50 pm

This is the basic code you need

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

The manager is given as a distinguished name. If you want the managers name then modify the code like this

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
   $_
}

if you want the data written back to a csv file then use 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

November 28, 2017 at 11:06 am

You can try the following command for manager information

Get-ADUser -server server_ip -Filter { mail -like "*" -and ObjectClass -eq "user" } `
-SearchBase "OU=Active Users,DC=eu,DC=ad,DC=some_company,DC=com" `
-Properties objectGUID,displayName,office,division,department,employeeNumber,
employeeID,mobilePhone,officePhone,ipphone,title,givenName,surname,mail,
@{Label="Manager";Expression={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}},
sAMAccountName |
Export-CSV "EU_AD_Properties.csv"

or

(get-aduser (get-aduser $user -Properties manager).manager).samaccountName

December 1, 2017 at 9:19 am

Hi

Apologies for the delayed reply. Thanks a lot the script worked for me.

Thanks
Raghav

December 7, 2017 at 12:55 pm

Hi

I used your script and it worked. When I run this script it is giving errors when the AD user not found in AD. How to capture the deleted users in the same script.

Thanks in advance
Raghav

December 7, 2017 at 1:33 pm

Untested, but something like this:

Import-Csv -Path .\names.csv |
foreach {
   try {
      $user = Get-ADUser -Identity $_.userid -Properties Manager
      $manager = Get-ADUser -Identity $user.Manager | select -expand Name
   } catch {
      $manager = "Invalid User ID or Manager"
   }

   $_ | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $manager
   $_

} | Export-Csv -Path names2.csv -NoTypeInformation