This script connects to Exchange Online, retrieves all mailboxes, and matches each mailbox with a corresponding Active Directory (AD) user based on the primary SMTP address. It then filters out email addresses from a specified excluded domain and formats the remaining proxy addresses. These filtered proxy addresses are then added to the AD user. The script also includes error handling for cases where no or multiple matching AD users are found, and logs any issues with updating the AD user.
Here is the Script:
# Define the Exchange Online organization and excluded domain
$Organization = "xxx.com"
$ExcludeDomain = "xxx.onmicrosoft.com"
# Connect to Exchange Online
Connect-ExchangeOnline -Organization $Organization -ErrorAction Stop
# Get all mailboxes
$AllMailboxs = Get-Mailbox
# Get all Active Directory users
$AllADUsers = Get-ADUser -Filter *
# Loop through each mailbox
foreach ($Mailbox in $AllMailboxs) {
# Find the corresponding AD user based on the mailbox's primary SMTP address
$ADUser = $AllADUsers | Where-Object EmailAddress -eq $($Mailbox.PrimarySmtpAddress)
# Handle different scenarios based on the number of matching AD users
switch ($ADUser.count) {
0 { Write-Warning "No AD User found with $($Mailbox.PrimarySmtpAddress) E-mail address" }
{$_ -gt 1} { Write-Warning "Multiple AD Users found with $($Mailbox.PrimarySmtpAddress) E-mail address" }
1 {
# Filter out addresses with excluded domain and correct formatting
$Addresses = $Mailbox.EmailAddresses | Where-Object {($_ -like "smtp:*") -and ($_ -notlike "*$ExcludeDomain")}
if ($Addresses) {
# Correct formatting for proxy addresses
$Addresses = $Addresses -creplace "SMTP:", "smtp:"
# Prepare hash to add proxy addresses
$HashToAdd = @{'proxyAddresses' = $Addresses}
try {
# Update the AD user with new proxy addresses
$ADUser | Set-ADUser -Add $HashToAdd -ErrorAction Stop
Write-Output "Updated $($Mailbox.EmailAddresses) proxyAddresses successfully"
}
catch {
Write-Output "Failed to update $($Mailbox.EmailAddresses) proxyAddresses. Error: $($_.Exception.Message)"
}
}
}
}
}