I am running the script below in exchange management shell. The purposed of this is, I want to add a list of emails from an excel file (file has two columns, names and email) to a group. So as you can see, i've imported the excel, added the group and loop for each member in the excel to add to the group.
The problem is, I'm getting "user with email not found" for a large number of names even if they definitely exist. It's probably around 40% found and 60% not found even if I can verify that the email does exist. Wondering if anyone can see an issue in the script I posted below.
$csvPath = "C:\Users\Desktop\emailNames.csv"
# Replace with the name of the distribution group
$groupName = "emailOfficer"
# Import the CSV file
$members = Import-Csv -Path $csvPath
# Loop through the CSV and add members to the distribution group
foreach ($member in $members) {
$email = $member.email.Trim()
$user = Get-Mailbox | Where-Object { $_.PrimarySMTPAddress -ieq $email.Trim() }
# $user = Get-Mailbox | Where-Object { $_.PrimarySMTPAddress -ilike "*$email*" }
Write-Host($user)
if ($user) {
Add-DistributionGroupMember -Identity $groupName -Member $user.Identity
Write-Host "Added $($user.PrimarySMTPAddress ) to $groupName"
} else {
Write-Host "User with email $email not found."
}
}