PowerShell Script for Adding SafeSender to All Mailboxes

turned-on MacBook Pro wit programming codes display
# Ensure ExchangeOnlineManagement module is installed and imported
if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
    Write-Host "Installing ExchangeOnlineManagement module..."
    Install-Module -Name ExchangeOnlineManagement -Force
}
Import-Module ExchangeOnlineManagement

# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName "[email protected]"

# Fetch all mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited

# Define trusted sender email/domain
$trustedSenderDomain = "[email protected]"

# Loop through mailboxes and add trusted sender
foreach ($mailbox in $mailboxes) {
    $mailboxId = $mailbox.UserPrincipalName  # safer unique identifier
    Write-Host "Processing mailbox: $mailboxId"

    try {
        # Get current junk email configuration
        $junkEmailConfig = Get-MailboxJunkEmailConfiguration -Identity $mailboxId

        if ($null -eq $junkEmailConfig) {
            Write-Warning "Could not retrieve Junk Email configuration for $mailboxId. Skipping."
            continue
        }

        # Check if domain is already trusted
        if ($junkEmailConfig.TrustedSendersAndDomains -notcontains $trustedSenderDomain) {
            $junkEmailConfig.TrustedSendersAndDomains.Add($trustedSenderDomain)

            # Update mailbox junk email config
            Set-MailboxJunkEmailConfiguration -Identity $mailboxId -TrustedSendersAndDomains $junkEmailConfig.TrustedSendersAndDomains
            Write-Host "Added trusted sender for $mailboxId"
        }
        else {
            Write-Host "Trusted sender already exists for $mailboxId"
        }
    }
    catch {
        $errorMessage = $_.Exception.Message
        Write-Warning ("Failed to process " + $mailboxId + ": " + $errorMessage)
    }
}

# Disconnect session
Disconnect-ExchangeOnline -Confirm:$false

Write-Host "All done!"

Works only on PowerShell 7. Follow the steps. It will be alright!