m365 get all forwarding rules

# Temporarily set the execution policy to bypass for this session
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force

# Check for the ExchangeOnlineManagement module and update or install as necessary
$module = Get-Module -Name ExchangeOnlineManagement -ListAvailable

if ($module -ne $null) {
    # Module is installed, attempt to update it
    Write-Host "ExchangeOnlineManagement module is installed. Checking for updates..."
    Update-Module -Name ExchangeOnlineManagement -Force
} else {
    # Module is not installed, install it
    Write-Host "ExchangeOnlineManagement module is not installed. Installing..."
    Install-Module -Name ExchangeOnlineManagement -Force
}

# Confirm the module is up to date
Write-Host "ExchangeOnlineManagement module is up to date."
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName youradminuser@yourdomain.com

# After connection, retrieve the domain from the connected session
$userPrincipalName = (Get-ExoMailbox -Identity youradminuser@yourdomain.com).UserPrincipalName
$domain = $userPrincipalName.Split("@")[1]
$mailboxes = Get-Mailbox -ResultSize Unlimited
$forwardingRules = @()

foreach ($mailbox in $mailboxes) {
    $rules = Get-InboxRule -Mailbox $mailbox.Identity | Where-Object { $_.ForwardTo -or $_.ForwardAsAttachmentTo -or $_.RedirectTo }
    foreach ($rule in $rules) {
        $obj = New-Object PSObject -Property @{
            Mailbox = $mailbox.PrimarySmtpAddress
            RuleName = $rule.Name
            ForwardTo = $rule.ForwardTo
            ForwardAsAttachmentTo = $rule.ForwardAsAttachmentTo
            RedirectTo = $rule.RedirectTo
        }
        $forwardingRules += $obj
    }
}

$mailboxForwarding = Get-Mailbox -ResultSize Unlimited | Where-Object { $_.ForwardingSmtpAddress -or $_.ForwardingAddress } | Select-Object DisplayName, ForwardingSmtpAddress, ForwardingAddress
# Ensure the output directory exists
$OutputDirectory = "C:/temp/"
If (-not (Test-Path -Path $OutputDirectory)) {
    New-Item -ItemType Directory -Force -Path $OutputDirectory
}

# Export forwarding rules to a text file
$forwardingRules | Format-Table | Out-File -FilePath "${OutputDirectory}${domain}_forwardingRules.txt"

# Export mailbox-level forwarding to a text file
$mailboxForwarding | Format-Table | Out-File -FilePath "${OutputDirectory}${domain}_mailboxForwarding.txt"

Leave a Reply

Your email address will not be published. Required fields are marked *