r/PowerShell • • Oct 22 '26

Question Exchange (Online) Powershell auto-forward and auto-reply

Ok, I need some help with Powershell.

Part of our company got sold. This weekend, the migration is set to go through. All users that are part of this transfer will login into the new owners IT infrastructure and their 365 tenant starting next monday. The mailbox contents will be synced and for the next few weeks all incoming e-mail needs to be auto-forwarded to the user's new mailbox in the other tenant. And a auto-reply will be sent to the sender informing them of the upcoming discontinuation of the old e-mail address.

So, all e-mail coming in to 'olduser' needs to be forwarded to 'newuser' and newuser is in another tenant. To prevent double e-mail, 'olduser' should not be seeing the e-mail in their inbox.

Currently this is what I have, being run from Exchange Management shell connected to Exchange Online

$Users = Import-Csv "c:\temp\usermailboxentest.csv" -delimiter ";"

foreach ($User in $Users) {

    Set-Mailbox -Identity $User.adresold `
        -ForwardingSmtpAddress $User.adresnew `
        -DeliverToMailboxAndForward $false
}

And then, I run this

$CsvPath = "C:\Temp\mailboxes.csv"

$StartTime = Get-Date
$EndTime   = [datetime]::new(2026, 12, 30, 23, 59, 59)

$Results = foreach ($CsvUser in Import-Csv -Path $CsvPath) {

    $MailboxAddress = $CsvUser.MailboxAddress.Trim()

    try {
        Write-Host "Processing: $MailboxAddress" -ForegroundColor Cyan

        # Retrieve the mailbox
        $Mailbox = Get-Mailbox -Identity $MailboxAddress -ErrorAction Stop

        # Determine the configured forwarding address
        if ($Mailbox.ForwardingSmtpAddress) {

            # Forwarding to an SMTP address
            $ForwardAddress = $Mailbox.ForwardingSmtpAddress.ToString() `
                -replace '(?i)^smtp:', ''
        }
        elseif ($Mailbox.ForwardingAddress) {

            # Forwarding to an internal Exchange recipient
            $ForwardRecipient = Get-Recipient `
                -Identity $Mailbox.ForwardingAddress `
                -ErrorAction Stop

            $ForwardAddress = $ForwardRecipient.PrimarySmtpAddress.ToString()
        }
        else {
            throw "No mailbox-level forwarding address is configured."
        }

        Write-Host "Forwarding address: $ForwardAddress" -ForegroundColor Green

        # Create the HTML automatic-reply message
        $AutoReplyMessage = @"
<p><strong>Dear Sender,</strong></p>

<p>
This email address has been discontinued etc. etc etc. and a variable for $ForwardAddress pointing the user to whatever the new e-mail address is.
</p>
"@

        # Configure automatic replies for internal and external senders
        Set-MailboxAutoReplyConfiguration `
            -Identity $MailboxAddress `
            -AutoReplyState Scheduled `
            -StartTime $StartTime `
            -EndTime $EndTime `
            -InternalMessage $AutoReplyMessage `
            -ExternalMessage $AutoReplyMessage `
            -ExternalAudience All `
            -ErrorAction Stop

        Write-Host "Automatic reply configured successfully." -ForegroundColor Green

        [PSCustomObject]@{
            MailboxAddress = $MailboxAddress
            ForwardAddress = $ForwardAddress
            Status         = "Success"
            Error          = ""
        }
    }
    catch {
        Write-Warning "Failed for $MailboxAddress`: $($_.Exception.Message)"

        [PSCustomObject]@{
            MailboxAddress = $MailboxAddress
            ForwardAddress = $null
            Status         = "Failed"
            Error          = $_.Exception.Message
        }
    }
}

# Show the results
$Results | Format-Table -AutoSize

# Export a processing report
$Results | Export-Csv `
    -Path "C:\Temp\AutoReplyResults.csv" `
    -NoTypeInformation `
    -Encoding UTF8

Now this is what happens, when I set DeliverToMailboxAndForward to $true, the autoreply works but the original e-mail is put into the old mailbox which I don't want to happen because in the new tenant users will end up with double e-mail because of the sync of mailbox contents.

When I set that to $false however, the autoreply doesn't work because 'olduser' mailbox is never 'hit'

Also, this will be for about 170 mailboxes, both user and shared boxes.

9 Upvotes

20 comments sorted by

2

u/schnitzeljaeger Oct 22 '26

Afaik this won't work with what MS gives you... Do you have a signature tool like the one from CodeTwo? With that one you could set up autoresponders sitting in front of the EOL infrastructure.

1

u/FastFredNL Oct 22 '26

Yeah that is what I'm finding out aswell now that I search google a bit. Great....

We don't have CodeTwo, we do have Exclaimer for our signatures but they don't seem to have such a function

2

u/BlackV Oct 22 '26

you should probably have a look too and removing those back ticks

$SetSplat = @{
    Identity         = $MailboxAddress
    AutoReplyState   = 'Scheduled'
    StartTime        = $StartTime
    EndTime          = $EndTime
    InternalMessage  = $AutoReplyMessage
    ExternalMessage  = $AutoReplyMessage
    ExternalAudience = 'All'
    ErrorAction      = 'Stop'
    }

Set-MailboxAutoReplyConfiguration @SetSplat

See here: Bye Bye Backtick: Natural Line Continuations in PowerShell for some good information

0

u/FastFredNL Oct 23 '26

I understand, but I really don't care about clean code, I just need it to work.

1

u/BlackV Oct 23 '26

Fair enough, tomask the silly question then, is this something better handled by a transport rule?

1

u/FastFredNL Oct 23 '26

Tried that, setting a transport rule to redirect an e-mail works for the forwarding part. But because the original mailbox doesn't get 'hit' there is no auto-reply

1

u/BlackV Oct 25 '26

Ah, no problem

2

u/Net-Runner Oct 23 '26

ForwardingSmtpAddress to an external domain gets blocked by the outbound spam policy unless auto-forwarding is set to On. Check that first, or the forwards will silently fail.

1

u/FastFredNL Oct 23 '26

Already done. 

1

u/fatalicus Oct 22 '26

What we did when migrating 70k or so users to new tenants is that we did a full migration, then incremental migrations once a day.

We then set an end date, and when that date came we stopped migrations and enabled forwarding and auto replies.

Realy only good way we found to avoid double emails in the new mailbox.

1

u/FastFredNL Oct 22 '26

Yeah only the sync should've been done by now. Cut off the sync during the migration weekend and then start autoforwarding and autoreply. That was the plan.

But the new owner was using Connectwise Backup and they got hacked last weekend. So the new owner and I set up CodeTwo today. That's simply not enough time.

1

u/capitolgood4 Oct 22 '26

This solution should work, and while you could build the automation in your tenant... why should you? Instead, you can put the configuration obligation onto the new tenant since it's now their customers that need the updated address information :D

  1. Run your first script as you have it to set DeliverToMailboxAndForward $false.
  2. Add all migrating mailboxes to a security group if you don't have one already.
  3. Create a transport rule targetting the security group and have it add a BCC to the autoreply mailbox in the new tenant.

     $transportRuleParams = @{
         Name                       = 'M&A: BCC Autoreply Intake for Divested Users'
         SentToMemberOf             = 'divested-users@OLDcompany.com'
         BlindCopyTo                = 'ma-autoreply@NEWcompany.com'
         ExceptIfFrom               = 'ma-autoreply@NEWcompany.com'
         ExceptIfMessageTypeMatches = 'AutoForward'
         ExceptIfSubjectContainsWords = @(
             'Automatic reply:',
             'Out of Office:',
             'Undeliverable:'
         )
         Priority                   = 0
     }
     New-TransportRule @transportRuleParams    

Then in the new tenant, they would need to:

  1. Create a new mailbox to manage autoreplies for all migrating mailboxes ('ma-autoreply@NEWcompany.com').
  2. Upload your csv with old and new address mapping to sharepoint.
  3. Create a PowerAutomate flow: targeting incoming messages to 'ma-autoreply@NEWcompany.com'; match recipient address to csv mapping file, reply to sender with message template that pulls the new email from the csv; delete the message from the mailbox.

1

u/capitolgood4 Oct 22 '26

AI spit this out for PowerAutomate, it's unchecked but may be helpful if you choose to go that route.

Power Automate Cloud Flow Implementation

Log into Power Automate using the service account (svc-powerautomate@NEWcompany.com) and build an Automated Cloud Flow:


Step 1: Trigger

  • Connector: Office 365 Outlook → When a new email arrives in a shared mailbox (V2)
  • Original Mailbox Address: ma-autoreply@NEWcompany.com
  • Include Attachments: No

Step 2: Loop & Noise Suppression Condition

Add a Condition control set to OR (if any condition is met, skip directly to cleanup in Step 5):

  • toLower(triggerOutputs()?['body/from']) contains mailer-daemon

  • toLower(triggerOutputs()?['body/from']) contains postmaster

  • toLower(triggerOutputs()?['body/from']) contains no-reply

  • toLower(triggerOutputs()?['body/from']) contains noreply

  • triggerOutputs()?['body/subject'] starts with Automatic reply:

  • triggerOutputs()?['body/subject'] starts with Undeliverable:

  • If Yes Branch: Jump directly to Delete email (V2) (Step 5) to purge the noise message.

  • If No Branch: Proceed to Step 3.


Step 3: Parse Target Recipients (To and Cc Consolidation)

Because an email may have the divested user in either the To or Cc line (or include multiple divested users on the same thread):

  1. Add a Compose action named Combine_Recipients:

    • Inputs:
      @{split(concat( coalesce(triggerOutputs()?['body/toRecipients'], ''), ';', coalesce(triggerOutputs()?['body/ccRecipients'], '') ), ';')}
      
  2. Add a Filter array action named Filter_OLDcompany_Recipients:

    • From: @{outputs('Combine_Recipients')}
    • Condition: @contains(toLower(item()), '@OLDcompany.com') is equal to true

Step 4: Lookup Mapping and Send Personalized Autoreply

Add an Apply to each loop iterating over @{body('Filter_OLDcompany_Recipients')}:

  1. Inside the loop, add Get items (SharePoint connector):

    • Site Address: <Your IT SharePoint Site>
    • List Name: DivestedUserMapping
    • Filter Query: OLDcompany_Email eq '@{toLower(trim(item()))}'
    • Top Count: 1
  2. Add a Condition (Check_Mapping_Found):

    • length(outputs('Get_items')?['body/value']) is greater than 0
  3. If Yes (Match Found):

    • Add action: Send an email from a shared mailbox (V2)
    • Original Mailbox Address: ma-autoreply@NEWcompany.com
    • To: @{triggerOutputs()?['body/from']}
    • Subject: Update regarding your email to @{toLower(trim(item()))}
    • Body:

      Hello,

      The division you contacted has transitioned to NEWcompany. The person you reached out to (@{toLower(trim(item()))}) now has a new email address: @{first(outputs('Get_items')?['body/value'])?['NEWcompany_Email']}.

      Your original message has been automatically forwarded to their new mailbox, so there is no need to resend it. Please update your address book for future correspondence.

  4. If No (Fallback - Recipient not in list or was BCC'd):

    • (Optional) Outside the loop, if length(body('Filter_OLDcompany_Recipients')) equals 0 or if no match was found, send a generic divisional transition notice without a specific user address.

Step 5: Shared Mailbox Cleanup

Outside the loop (at the very bottom of the flow), add Delete email (V2) (Office 365 Outlook connector):

  • Message Id: @{triggerOutputs()?['body/id']}
  • Original Mailbox Address: ma-autoreply@NEWcompany.com

1

u/ashimbo Oct 24 '26

Stop forwarding, and let the sync handle it.

0

u/BlackV Oct 22 '26

and for the next few weeks all incoming e-mail needs to be auto-forwarded to the user's new mailbox in the other tenant.

ouch, why not add that domain as an alias/mx on the new tennant ?

2

u/FastFredNL Oct 22 '26

Because the domain remains ours and is not being transferred to the new tennant. Last I checked you can't have 1 domain active on 2 different tennants at the same time?

0

u/BlackV Oct 22 '26

Because the domain remains ours

? oh though the company got sold and you're moving to the new tenant

2

u/FastFredNL Oct 23 '26

Company does a number of things within the same industry and has decided to focus more on one single thing. So sell one part including sites, machinery, users and keep the rest.

1

u/BlackV Oct 25 '26

Thanks the details, I must have missed that in the op