This is what I've cobbled together so far:
$managers = Get-ADUser -Filter * -Properties name, directreports, EmailAddress | where {$_.directreports -ne $Null}
foreach ($i in $managers)
{
get-aduser -filter * -Properties DisplayName, directReports, enabled | Where{($_.directReports -Like "*") -And ($_.enabled -eq $True)} | select samAccountName, displayName | export-csv -path c:\temp\$i.csv
}
I feel like I'm close but each CSV is coming out the same, it's not listing the managers direct reports, it's listing all the managers. Also the filenames for the CSV are coming out CN=name,OU=name,DC=name,DC=name.csv which is not great but I could live with.
Any help is appreciated.
CodePudding user response:
I think below does what you want.
It loops through all users in AD that have their DirectReports attribute filled in and then loops over the array of user DistinguishedNames in there to get a list of user SamAccountNames and DisplayNames.
Per manager a csv file is created named using the manager's DisplayName:
# Get-ADUser by default already returns objects with these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
Get-ADUser -Filter * -Properties DisplayName, DirectReports |
Where-Object {$_.DirectReports} | ForEach-Object {
$manager = $_.DisplayName # or SamAccountName if that suits you better
$result = foreach ($user in $_.DirectReports) {
$adUser = Get-ADUser $user -Properties DisplayName
# output only enabled users
if ($adUser.Enabled) { $adUser | Select-Object SamAccountName, DisplayName }
}
# write out this managers csv file
$result | Export-Csv -Path "C:\Temp\$($manager).csv" -NoTypeInformation
}