Powershell : Return Department and OU from UPN list

I had a requirement to with a list of UPN names like for example  of this would be a user UPN of lee.croucher@pokebearswithsticks.com to then be looked up via ADDS and for the script to retrieve the department attribute and then return the OU for that user, this was all to save me looking up a large bunch of users (and doing it manually - yuck!)

# Import the Active Directory module

Import-Module ActiveDirectory

# Path to the file containing list of users
$userListFile = "users_UPN.txt"

# Read the list of users from the file
$userList = Get-Content $userListFile

# Initialize counter
$count = 0

# Iterate through each user in the list

foreach ($user in $userList) {

    # Look up the user by UPN

    $userObject = Get-ADUser -Filter {UserPrincipalName -eq $user} -Properties Department, DistinguishedName

    # Check if user was found

    if ($userObject -ne $null) {

        # Extract the department information

        $department = $userObject.Department

        # Extract the OU information from the DistinguishedName

        $ou = ($userObject.DistinguishedName -split ',',2)[1]

        # Check if the OU contains "Technology"

        if ($ou -like "*customer delivery*") {

            # Output the user, department, and OU information

            Write-Host "User: $($userObject.Name), Department: $($department), OU: $ou"        

            # Increment counter



    } else {

        Write-Host "User with UPN '$user' not found in Active Directory."



# Output count

Write-Host "Total users found in 'Technology' OU: $count"

That will then show you the username as  UPN, then the department as recorded in ADDS then the OU the account is located in AD, this script will also only show people the "Technology" OU - to remove this remove this section of the code:

  if ($ou -like "*Technology*")

The output should look like this:

User: lee@pokebearswithsticks.com, Department: Technology, OU: OU=Users,OU=Technology,OU=Users,DC=bear,DC=local

User: bear@pokebearswithsticks.com, Department: Technology, OU: OU: OU=Testers,OU=Users,OU=Technology,OU=Users,DC=bear,DC=local

Previous Post Next Post

Ω†Ω…ΩˆΨ°Ψ¬ Ψ§Ω„Ψ§ΨͺΨ΅Ψ§Ω„