Wednesday, January 24, 2018

Exchange - Changing from ForwardingAddress to ForwardingSMTPAddress for multiple mailboxes

Whoa, has it really been almost TWO YEARS since I've posted?  Well, if you still follow over here, be sure to follow me on twitter at https://twitter.com/chrislehratx - I tend to share out articles, blogs, and oneliners related to the Microsoft Exchange and/or Skype products over there.  Far more frequent updates than here.  But today, my script went from a one-liner to a multiliner, so I figured I would blog.

I had a weird need arise where users that were using ForwardingAddress were moved to the cloud, and the mail contact object that was selected for them was NOT synchronized to Azure AD, so it got stripped from the mailbox configuration.  The fix was to reference the mail contact per mailbox, get the SMTP address and then post a set-mailbox command with this data.

Script below - enjoy.

A few notes:

  1. In the get-mailbox, you can change the OU to a | where { $_.something -match ""} in order to capture your target list of mailboxes for your own situation.  I happened to have them all in an OU together.
  2. In the set-mailbox, this currently has a -whatif - you should NEVER ever do bulk AD updates without this first, so I left it in the script.

 # Get all the target mailboxes and assign to $x - change below to match your target audience as needed!
$x = get-mailbox -resultsize unlimited -organizationalunit "OU=TargetOU,OU=Users,OU=Mailboxes,DC=contoso,DC=com"
foreach ($mailbox in $x) {
# capture their SMTP address in the contact in a string
$SMTPforwardingaddress = ((get-mailcontact -Identity (((get-mailbox $mailbox).forwardingaddress).distinguishedname)).emailaddresses | where { ($_.isprimaryaddress -eq $true) -and ( $_.prefixstring -eq "SMTP")}).addressstring
# Null out their forwarding and replace with SMTPforwarding
write-host "Setting $mailbox to forward to $SMTPForwardingaddress"
set-mailbox -identity $mailbox -whatif -forwardingaddress $null -ForwardingSmtpAddress $SMTPforwardingaddress
}


If you like to understand Shell that one beast mode line broken out:

$SMTPforwardingaddress = ((get-mailcontact -Identity 
(((get-mailbox $mailbox).forwardingaddress).distinguishedname)).emailaddresses 


This does a get-mailbox, references the existing forwarding address object's DN, then the EmailAddresses, which is a ProxyAddresses format

| where { ($_.isprimaryaddress -eq $true) -and ( $_.prefixstring -eq "SMTP")}).addressstring


This captures what should be THE ONE address that is the primary and SMTP address (as opposed to X400)

And then once we have the string, the set-mailbox command nulls the ForwardingAddress and sets the string for ForwardingSMTPAddress

Finally - here's what it looks like (heavily redacted) when run (at least with -whatif still in there!)

No comments: