# Connect to AD and Exchange
if (-not(Get-Module -name "activedirectory")) { Import-Module ActiveDirectory | out-null }
Connect-ExchangeServer -auto
# Variables
$TargetDC = "10.0.0.1" #IP address of user AD Domain Controller
$TargetDCOU = "OU=Company,DC=user,DC=com" #Distinguished name of OU with users
$ShortDomainName = "USER\" #Short name of user AD
$LogFile = "C:\Script\Mail_Attribute\log.txt" #Path to the log file
# Get information from AD to hash tables
$arrSourceAD = @{}
$arrTargetAD = @{}
# Get Exchange Forest credential
$credentials_Mail = Get-Credential
Get-Mailbox -Credential $credentials_Mail -RecipientTypeDetails LinkedMailbox | ForEach-Object {$arrSourceAD.Add($_.LinkedMasterAccount,$_.PrimarySmtpAddress)}
# Get User Forest credential
$credentials = Get-Credential
Get-ADUser -Credential $credentials -Filter * -SearchBase $TargetDCOU -Server $TargetDC -Properties mail | ForEach-Object {$arrTargetAD.Add($_.SamAccountName,$_.mail)}
# Main
$date = (Get-Date).ToString()
$date | Out-File $LogFile -Append
ForEach ($TargetUser in $arrTargetAD.Keys){
$TargetUser1 = $ShortDomainName + $TargetUser
if ($arrSourceAD.ContainsKey($TargetUser1) -eq "True"){
if ($arrTargetAD.$TargetUser -ne $arrSourceAD.$TargetUser1){
$SourceUserEmail = $arrSourceAD.$TargetUser1
$TargetUserEmail = $arrTargetAD.$TargetUser
$TargetUserName = $TargetUser
$LogText = "$date. Account '$TargetUserName'. Attribute 'mail' has been changed from '$TargetUserEmail' to '$SourceUserEmail'."
Write-Output $LogText
# Write to the log file
$LogText | Out-File $LogFile -Append
# Write changes into the user account
Set-ADUser -Credential $credentials $TargetUserName -Server $TargetDC -Replace @{mail="$SourceUserEmail"}
}
}
}
I hope that Microsoft engineers will pay attention to this little issue and fix it in the next cumulative update or in the next generation of Exchange Server.
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)