When you have user in Active Directory they should be assigned a manager, however there will be some employees that do not have a manager set you can see this from the user properties in Active Directory if you choose the Organisation tab and then find the Manager field that will look like this:
If you are using Outlook then the quick steps of "Team email" and "To Manager" will also fail to function without a manager:
Bottom line here is, you need to keep a valid manager on your account, so how many accounts have no manager or have a $null value well that is where the script comes in, it will find all the people without a manager and give you a CSV file with all those juicy details contained within.
# Define the OU to search and the OUs to exclude
$searchOU = "OU=Employees,DC=bear,DC=local"
$excludeOUs = "OU=Terminated,OU=Employees,DC=bear,DC=local", "Inactive,OU=Employees,DC=bear,DC=local"
# Initialize an array to hold the results
$results = @()
# Get all users in the specified OU
$users = Get-ADUser -SearchBase $searchOU -Filter * -Properties Manager, Department
# Iterate over each user
foreach ($user in $users) {
# Check if the user is in any excluded OUs
$inExcludedOU = $excludeOUs | ForEach-Object { $user.DistinguishedName -like $_ } | Where-Object { $_ }
if (!$inExcludedOU) {
# Get the manager's distinguished name
$managerDn = $user.Manager
# Initialize manager UPN variable
$managerUpn = $null
# If the manager DN is not null, retrieve the manager's UPN
if ($managerDn) {
$manager = Get-ADUser -Identity $managerDn -Property UserPrincipalName
$managerUpn = $manager.UserPrincipalName
}
# Add the user, manager, and department to the results
$results += [PSCustomObject]@{
User = $user.UserPrincipalName
Manager = $managerUpn
Department = $user.Department
}
}
}
# Filter the results for users with no manager
$usersWithoutManager = $results | Where-Object { $_.Manager -eq $null }
# Count the number of users without a manager
$count = $usersWithoutManager.Count
# Export the results to a CSV file
$usersWithoutManager | Export-Csv -Path "MissingManager.csv" -NoTypeInformation
# Display the count of users without a manager
Write-Host "Number of users without a manager: $count"
When you run the script you will get a output like this, but that will give you the count which here is 1884 users:
The full report will be saved in the save folder from where the script is run and it will be called MissingManager.csv.