Deleting/Removing Mailboxes with Certain Mail Extension

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=$_}
IT_Admin XXXXAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vasil Michev (MVP)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:

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jason CrawfordTransport NinjaCommented:
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 EngineerCommented:
Comments BEFORE running in production?


Doing something like this, you want to be 100% sure it's not going to delete all mailboxes because you missed something.
IT_Admin XXXXAuthor 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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.