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
$count++
}
} else {
Write-Host "User with UPN '$user' not found in Active Directory."
}
}
# Output count
Write-Host "Total users found in 'Technology' OU: $count"
if ($ou -like "*Technology*")