This script automates the process of exporting transport rules from one Exchange Online tenant and importing them into another. It connects to the source Exchange tenant, exports the transport rule collection, disconnects, and then connects to the destination Exchange tenant to import the rules. The script also handles errors and ensures proper disconnection from both tenants after the operations are complete, making it useful for migrating transport rules between Exchange environments.
Here is the script:
$SourceExchange = ""
$DestinationExchange = ""
# Install the required module if not already installed
if (-not (Get-Module -Name ExchangeOnlineManagement -ListAvailable)) {
Write-Output "Installing ExchangeOnlineManagement module..."
Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber -Scope CurrentUser
}
# Import the module
Import-Module ExchangeOnlineManagement -Force
Write-Output "Connecting to the source Exchange: $SourceExchange"
Connect-ExchangeOnline -Organization $SourceExchange
try {
Write-Output "Exporting transport rule collection"
$file = Export-TransportRuleCollection
Write-Output "Disconnecting from the source Exchange"
Disconnect-ExchangeOnline
Write-Output "Connecting to the destination Exchange: $DestinationExchange"
Connect-ExchangeOnline -Organization $DestinationExchange
try {
Write-Output "Importing transport rule collection"
Import-TransportRuleCollection -FileData $file.FileData
Write-Output "Transport rule collection imported successfully"
}
finally {
Write-Output "Disconnecting from the destination Exchange"
Disconnect-ExchangeOnline
}
}
finally {
if ($Error) {
Write-Output "An error occurred: $($Error[0].Exception.Message)"
}
}