Deleting/Removing Mailboxes with Certain Mail Extension

IT_Admin XXXX
IT_Admin XXXX used Ask the Experts™
on
Dear experts,
Any suggestions or comments on the following script? It looks good but wanted to ask for some advice before we run this in production (and yes we tested this in test/lab but wanted to be 100% we are not missing other scenarios). The goal is to remove mailboxes that has .local extension. Please advise. Thank you!!

foreach($i in Get-Mailbox -ResultSize Unlimited) {
     $i.EmailAddresses |
       ?{$_.AddressString -like '*@.local'} | %{
          Set-Mailbox $i -EmailAddresses @{remove=$_}
         }
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2015
Distinguished Expert 2018
Commented:
You need to handle the scenario where this is the Primary smtp address, which means it cannot be removed without promoting another alias as primary. I have some examples on how to handle that here: https://www.michev.info/Blog/Post/2011/bulk-replacing-proxy-addresses-based-on-a-pattern

Also, $1 is not set, you should use something like $i.ExchangeGuid.ToString()

Commented:
I think this would serve you better:
foreach($i in (Get-Mailbox -ResultSize unlimited)) {
  foreach ($a in $i.EmailAddresses) {
    if ($a -like '*.local') {
      $i.EmailAddresses.Remove('smtp:' + $a)
    }
  }
}

Open in new window

Scott CSenior Engineer

Commented:
Comments BEFORE running in production?

RUN IT IN A TEST ENVIRONMENT!!!!

Doing something like this, you want to be 100% sure it's not going to delete all mailboxes because you missed something.

Author

Commented:
@Scott C - Yeah I know that :). I did that and just wanted to make sure I'm not factoring out any other gotchas and issues.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial