Active directory : How to get a list of all active directory users with direct reports

In this tutorial we find all users who have direct reports to them, in theory we should be able to find these users by their job role, but this would only work if we had a well-maintained AD but this is so often not the case

Import the users from AD

The first step is to extract all the users of interest and store them in a variable. In my search I used the -SearchBase command to target my ‘Sites’ OU. You can leave this Section out if you want to search your entire domain


$managers = Get-ADUser -Filter * -Properties name, directReports | SORT name


Create an empty array variable

Next we need to create an empty array to store all the entries we find.


$newman = @()


Process users in foreach loop

Now we have our variables set up we need to run them through a foreach loop
$staff : This collects any users that are stored in the ‘directreports’ field in AD
$count : Counts the number (if any) of people that report to that person


foreach ($man in $managers){
$staff = $man.directReports
$count = $staff.Count


Create an if statement

Within the foreach loop we create an if statement which says 'if the variable called $count has any number greater than 0 add the name stored in $man variale into our new variable called $newman'. The thoery here is that if the user has 0 direct reports to him we are not interested in this user.


if ($count -gt 0){
$newman += $man.SamAccountName
}
}


The full script

$managers = Get-ADUser -Filter * -SearchBase "OU=sites,DC=barrett,DC=Local" -Properties name, directReports | SORT name
$newman = @()
cls
foreach ($man in $managers){
$staff = $man.directReports
$count = $staff.Count

if ($count -gt 0){
$newman += $man.SamAccountName
}
}


Cut & Paste


Comments
// Collect comments ''
Search