# get-dllastused # This script retrieves all distribution groups and checks the last email received for each group in the past 90 days. # Special handling of 10 day limit and throttling 100 query requests are accepted within a 5 minute running window = 20/Minute = 1 every 3 seconds. # To avoid throttling, the script will wait 1 second between each query and will check the time since the last query to ensure it does not exceed the limit. param ( [string]$csvfilename = "DistributionGroupsLastUsed.csv" ) Write-Host "get-dllastused: Start" Write-Host "Retrieving distribution groups and their last email received in the past $Days days..." Write-Host "May take some time depending on the number of groups and email traffic." $groups = Get-DistributionGroup -ResultSize unlimited Write-Host "Total groups retrieved: $($groups.Count)" Write-Host "Processing groups..." -ForegroundColor Green $count = 0 $lastcall = get-date foreach ($group in $groups) { $count++ Write-Host "Group($count/$($groups.Count)): $($group.DisplayName) ($($group.PrimarySmtpAddress)) Days back" -NoNewline ForEach ($intervall in 1..9) { Write-Host " $($intervall*10)" -nonewline # Throttling to prevent blocked $delay = [math]::Max(0, (3-((get-date) - $lastcall).TotalSeconds)) if ($delay -gt 0) { Write-Host "T$($delay)Sec " -ForegroundColor Yellow -NoNewline Start-Sleep -Seconds $delay } #Start-Sleep -Seconds [math]::Max(0, (3-((get-date) - $lastcall).TotalSeconds)) $lastcall = get-date $lastMail = Get-MessageTraceV2 ` -RecipientAddress $group.PrimarySmtpAddress ` -StartDate (Get-Date).AddDays(-($intervall*10)) ` -EndDate (Get-Date).AddDays(-($intervall*10 - 10)) ` | Sort-Object Received -Descending ` | Select-Object -First 1 if ($lastMail) { Write-Host " Found: $($lastMail.Received)" -ForegroundColor Green break } } Write-Host "lastMail: $($lastMail.Received)" $result = [PSCustomObject]@{ GroupName = $group.DisplayName Email = $group.PrimarySmtpAddress LastMail = $lastMail.Received LastSender = $lastMail.SenderAddress LastSubject = $lastMail.Subject } if ($csvfilename) { $result | Export-Csv -Path $csvfilename -Append -NoTypeInformation } else { $result } } Write-Host "get-dllastused: End"