简体   繁体   中英

Get AD users’ manager and primary group that is associated with a user's manager

I am new to PowerShell scripting. I am trying to export users' manager data from AD to a csv file. I created a PowerShell script that Get users' manager data from AD which are as follows:

name, samaccountName, email address 

and primary group that is associated with the manager and the user he managed.

I import a user.csv file in the code to retrieve the manager data and then export the data to user_manager.csv . My code doesn't work. Can you please help me?

Here is import file, user.csv :

id        userid      groups  
-----------------------------
1         fiyx        f0302        
2         bise        acct     
3         misye       d4029        
4         suew        sales   

Here's the code:

Import-Csv -Path "\tmp\user.csv" |
$user = Get-ADUser -Identity $_.userid -Properties manager
$group  = Get-ADGroup -Identity $_.group.userid -Properties groups
 $_ | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $manager.Name
$manager = Get-ADUser -Identity $user.Manager -Properties samaccountname, displayName, mail
 $_

} | Export-CSV -Path "C:\tmp\manager_user.csv" –NoTypeInformation

Below is the result that I want to see in user_manager.csv:

userid    groups     manager       samaccountname     mail  
---------------------------------------------------------------------------   
fiyx      f0302      Brian Lee      brinle           brian.lee@creek.com
bise      acct       Susan Brisky   Susbri           susan.brisky@creek.com
misye     d4029      Mary Louname   marloun          mary.louname@creek.com
suew      sales      Wuson Tacos    wusta            wuson.tacos@creek.com

Please always add the errors you're getting to the post, that way we don't have guess where the issues may occur. I didn't get the pipe at the end of the first line. Sometimes a loop helps to make scripts a bit more readable. This should work:

$data = Import-Csv -Path "\tmp\user.csv"
foreach ($entry in $data){
    $user = Get-ADUser -Identity $entry.userid -Properties manager
    $manager = Get-ADUser -Identity $user.Manager -Properties samaccountname, displayName, mail
    $entry | Add-Member -MemberType NoteProperty -Name 'Manager' -Value $manager.Name
    $entry | Add-Member -MemberType NoteProperty -Name 'samaccountname' -Value $manager.samaccountname
    $entry | Add-Member -MemberType NoteProperty -Name 'mail' -Value $manager.mail
}

$data | Export-CSV -Path "C:\tmp\manager_user.csv" –NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM