Find external forwarding mailboxes in Office 365 with PowerShell

Find External Forwarding Mailboxes in all Office 365 Customer tenants

This is the single Office 365 tenant version of this script. It checks all Office 365 mailboxes for external forwarding addresses. External forwarders are commonly used by hackers and bad actors to exfiltrate data from an organisation.

How to find external forwards on Office 365 mailboxes

  1. Double click the script below, copy and paste it into Visual Studio Code
  2. Safe it as a PowerShell (.ps1) file
  3. Press F5 to run it
  4. Enter the credentials of an Exchange or Global admin
  5. A list of any external forwarders will be exported to c:\temp\externalforward.csv

 

PowerShell script to detect external forwards on Office 365 Mailboxes

 

$credentials = Get-Credential
Write-Output "Getting the Exchange Online cmdlets"
   
$Session = New-PSSession -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
    -ConfigurationName Microsoft.Exchange -Credential $credentials `
    -Authentication Basic -AllowRedirection
Import-PSSession $Session

$mailboxes = Get-Mailbox -ResultSize Unlimited
$domains = Get-AcceptedDomain
 
foreach ($mailbox in $mailboxes) {
 
    $forwardingSMTPAddress = $null
    Write-Host "Checking forwarding for $($mailbox.displayname) - $($mailbox.primarysmtpaddress)"
    $forwardingSMTPAddress = $mailbox.forwardingsmtpaddress
    $externalRecipient = $null
    if ($forwardingSMTPAddress) {
        $email = ($forwardingSMTPAddress -split "SMTP:")[1]
        $domain = ($email -split "@")[1]
        if ($domains.DomainName -notcontains $domain) {
            $externalRecipient = $email
        }
 
        if ($externalRecipient) {
            Write-Host "$($mailbox.displayname) - $($mailbox.primarysmtpaddress) forwards to $externalRecipient" -ForegroundColor Yellow
 
            $forwardHash = $null
            $forwardHash = [ordered]@{
                PrimarySmtpAddress = $mailbox.PrimarySmtpAddress
                DisplayName        = $mailbox.DisplayName
                ExternalRecipient  = $externalRecipient
            }
            $ruleObject = New-Object PSObject -Property $forwardHash
            $ruleObject | Export-Csv C:\temp\ExternalForward.csv -NoTypeInformation -Append
        }
    }
}

Was this article helpful?

Related Articles