BoBeB good Spot have added a filter to fix this Where-Object { $_.RecipientAddress -notlike "*@$($mailbox.PrimarySmtpAddress.Split('@')[1])" }
#Connect EXOL
Connect-ExchangeOnline
# Define the threshold for unique recipients
$threshold = 2000
# Get the current date and time
$now = Get-Date
# Calculate the start and end date for the 24-hour period
$startDate = $now.AddDays(-1)
$endDate = $now
# Get all mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited
# Iterate through each mailbox
foreach ($mailbox in $mailboxes) {
# Get the externally sent messages for the specified period
$sentMessages = Get-MessageTrace -SenderAddress $mailbox.PrimarySmtpAddress -StartDate $startDate -EndDate $endDate | Where-Object { $_.RecipientAddress -notlike "*@$($mailbox.PrimarySmtpAddress.Split('@')[1])" }
# Count the unique recipients
$uniqueRecipients = $sentMessages.RecipientAddress | Select-Object -Unique
# Check if the number of unique recipients exceeds the threshold
if ($uniqueRecipients.Count -gt $threshold) {
Write-Host "Mailbox $($mailbox.PrimarySmtpAddress) has sent to $($uniqueRecipients.Count) unique recipients in the last 24 hours."
}
}