Hi all
I have a list of users in a CSV file, and I want to retrieve their managers’ email addresses. However, when I use the syntax below, I don’t get any output. I have both UPNs and sAMAccountNames, and the CSV file contains the sAMAccountNames.

i have csv file in below format.
sam
user1
user2

$requestedUsers = Import-Csv "C:\temp\input.csv"

$allUsers = Get-ADUser -filter 'Enabled -eq $true' -Properties Displayname, EmailAddress, Manager

$filterdUsers = $allUsers |
Where-Object { $_.SamAccountName -in $requestedUsers.sam }  
$report = foreach ($user in $filterdUsers) {
    $managerEmail = $allUsers |
    Where-Object DistinguishedName -eq $user.Manager |
    Select-Object -ExpandProperty EmailAddress

    [PSCustomObject][ordered]@{
        DisplayName  = $user.DisplayName
        EmailAddress = $user.EmailAddress
        ManagerEmail = $managerEmail
    }
}

$report | export-csv c:\temp\output.csv -Notypeinformation
5 Spice ups

Instead of filtering $allUsers again, use Get-ADUser to directly retrieve the manager’s details using their distinguished name.

Initialize $report as an array before the loop to store the results

See one I wrote earlier

# Import the CSV file
$requestedUsers = Import-Csv "C:\temp\input.csv"

# Retrieve all enabled users with the necessary properties
$allUsers = Get-ADUser -filter 'Enabled -eq $true' -Properties DisplayName, EmailAddress, Manager

# Filter users based on sAMAccountName from the CSV file
$filteredUsers = $allUsers | Where-Object { $_.SamAccountName -in $requestedUsers.sam }

# Initialize an array to store the report
$report = @()

# Loop through each filtered user to get their manager's email address
foreach ($user in $filteredUsers) {
    $manager = Get-ADUser -Identity $user.Manager -Properties EmailAddress
    $managerEmail = $manager.EmailAddress
    # Create a custom object for the report
    $report += [PSCustomObject][ordered]@{
        DisplayName  = $user.DisplayName
        EmailAddress = $user.EmailAddress
        ManagerEmail = $managerEmail
    }
}

# Export the report to a CSV file
$report | Export-Csv -Path "C:\temp\output.csv" -NoTypeInformation

4 Spice ups