This script imports a CSV file containing mailbox data and matches each mailbox with a corresponding Active Directory (AD) user based on their primary SMTP address. For each matched user, it updates the `msExchHideFromAddressLists` attribute, controlling whether the mailbox is hidden from the Global Address List (GAL). The script checks for scenarios like no matching AD user or multiple matches and handles any errors encountered during the update process.
Here is the script:
$ExcludeDomain = "XXX.onmicrosoft.com"
$CSVPath = "$home\desktop\csvfile.csv"
$AllMailboxs = Import-Csv -Path $CSVPath
# Get all Active Directory users
$AllADUsers = Get-ADUser -Filter * -Property "msExchHideFromAddressLists"
# 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.EMAILFROMAD)
# Handle different scenarios based on the number of matching AD users
switch ($ADUser.count) {
0 { Write-Warning "No AD User found with $($Mailbox.EMAILFROMAD) E-mail address" }
{$_ -gt 1} { Write-Warning "Multiple AD Users found with $($Mailbox.EMAILFROMAD) E-mail address" }
1 {
try {
$hash = @{msExchHideFromAddressLists ="$($Mailbox.HIDEGAL)"}
$ADUser | -Replace $hash -ErrorAction Stop
Write-Output "Updated $($Mailbox.EMAILFROMAD) Hide from GAL Attribute Successfully"
}
catch {
Write-Output "Failed to update $($Mailbox.EMAILFROMAD) Hide from GAL Attribute. Error: $($_.Exception.Message)"
}
}
}
}