Connect-ExchangeOnline
$UserEmails = @("user1@acmecorp.com")
$StartDate = (Get-Date).AddDays(-10).Date
$EndDate = Get-Date
$finalReport = foreach ($Email in $UserEmails) {
# 1. Fetch Sent Messages
$sentTraces = Get-MessageTraceV2 -SenderAddress $Email -StartDate $StartDate -EndDate $EndDate -ResultSize 5000 |
Select-Object MessageId, Received, @{Name='Direction'; Expression={'Sent'}}
# 2. Fetch Received Messages
$receivedTraces = Get-MessageTraceV2 -RecipientAddress $Email -StartDate $StartDate -EndDate $EndDate -ResultSize 5000 |
Select-Object MessageId, Received, @{Name='Direction'; Expression={'Received'}}
# Combine both datasets
$allTraces = $sentTraces + $receivedTraces
# Deduplicate based on MessageId AND Direction (handles internal emails to self correctly)
$uniqueEmails = $allTraces | Group-Object MessageId, Direction | ForEach-Object {
$firstEntry = $_.Group[0]
[PSCustomObject]@{
Direction = $firstEntry.Direction
Date = $firstEntry.Received.Date
}
}
# Group strictly by Date to combine Sent and Received into a single row
$uniqueEmails | Group-Object Date | ForEach-Object {
# Filter the group's internal items to count Sent vs Received
$sentCount = ($_.Group | Where-Object { $_.Direction -eq 'Sent' }).Count
$receivedCount = ($_.Group | Where-Object { $_.Direction -eq 'Received' }).Count
[PSCustomObject]@{
UserAddress = $Email
Date = [datetime]$_.Name
SentCount = if ($sentCount) { $sentCount } else { 0 }
ReceivedCount = if ($receivedCount) { $receivedCount } else { 0 }
}
}
}
# Output the flattened results
$finalReport | Sort-Object Date, UserAddress | Out-GridViewWas this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article