Powershell : Report on people with no manager (and more)

I got asked the other day if I could query Active Directory for any user that does not have a manager and more interestingly I would need to report who the managers were for all the people in a certain OU.

This did not concern privileged accounts or any service accounts, but any accounts created in the "Users" OU which here will be called "Employees"

I also need to exclude on OU from this script and I require a couple of CSV files to be exported for analytical purposes.

Script : GlobalManagerCheck.ps1

# Define whether to export to CSV
$exportToCsv = $true  # Set to $false if you don't want to export

# Define the paths for the CSV files (optional)
$nullManagerCsvPath = "NoManagerReport.csv"
$allUsersCsvPath = "AllManagers.csv"

# Define the base OU to search
$baseOU = "OU=Employees,DC=bear,DC=local"

# Define the OU to exclude
$excludeOU = "OU=BlitzedEmployees,OU=Employyes,DC=bear,DC=local"

# Search for all users in the base OU
$allUsers = Get-ADUser -Filter * -SearchBase $baseOU -Property DisplayName, SamAccountName, Manager, DistinguishedName

# Exclude users in the 'Deleted Accounts' OU
$filteredUsers = $allUsers | Where-Object { $_.DistinguishedName -notlike "*$excludeOU*" }

# Filter users who have a null manager
$usersWithoutManager = $filteredUsers | Where-Object { -not $_.Manager }

# Report on users with a null manager
$usersWithoutManagerCount = $usersWithoutManager.Count
Write-Host "`nUsers with a null manager ($usersWithoutManagerCount):"
$nullManagerReport = $usersWithoutManager | Select-Object SamAccountName, DisplayName
$nullManagerReport | Format-Table -AutoSize

# Report on all users and their managers
$allUsersCount = $filteredUsers.Count
Write-Host "`nAll users and their managers ($allUsersCount):"
$allUsersReport = $filteredUsers | Select-Object SamAccountName, DisplayName, @{Name="Manager";Expression={(Get-ADUser $_.Manager -Property DisplayName).DisplayName}}
$allUsersReport | Format-Table -AutoSize

# CSV Export

if ($exportToCsv) {
   Write-Host "`nExporting reports to CSV..."
    $nullManagerReport | Export-Csv -Path $nullManagerCsvPath -NoTypeInformation
    $allUsersReport | Export-Csv -Path $allUsersCsvPath -NoTypeInformation
    Write-Host "CSV export completed. Files saved to:"
    Write-Host " - Null Manager Report: $nullManagerCsvPath"
    Write-Host " - All Users Report: $allUsersCsvPath"
}

# Output count of each list
Write-Host "`nSummary:"
Write-Host "Total users found (excluding '$excludeOU'): $allUsersCount"
Write-Host "Total users without a manager: $usersWithoutManagerCount"

When this script it run it should look like this, depending on the size of your Active Directory will depend on how long the report takes to complete.




Previous Post Next Post

نموذج الاتصال