Powershell : UPN input to lookup Manager & Department


I went on another mission today where I had a list of UPN details for users, and the ask was:

Who did they report to?
What department do they work for?

I immediately thought this is simple as those questions can be fixed with the script, all of this information is stored in Active Directory.

If you are managing your users correctly, each user should have a manager and a department, however, there is a chance that some users will not have a manager set.

This means we need to build some error correction into our script, Obviously, if it tries to query a list of users, and they don’t have managers, you will get errors in your script to say that cannot be no “null” - in this instance, the best thing to do is just leave the manager field blank.

We then need the user the manager and the department outputting in a nice table.

Script : UPNtoManager.ps1

# Define the path to the file containing the UPNs
$upnFilePath = "upn.txt"

# Read the UPNs from the file
$upns = Get-Content -Path $upnFilePath

# Initialize an array to hold the results
$results = @()

# Iterate over each UPN
foreach ($upn in $upns) {

# Get the user object from Active Directory
   $user = Get-ADUser -Filter {UserPrincipalName -eq $upn} -Property Manager, Department

# If the user is found
    if ($user) {

# 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
        }
    } else {

# If the user is not found, add an entry with null values
        $results += [PSCustomObject]@{
            User = $upn
            Manager = $null
            Department = $null
        }
    }
}

# Display the results in a table format
$results | Format-Table -AutoSize

This will then output all your data in a table like this (redacted for privacy)



Previous Post Next Post

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