# This script retrieves message tracking logs for emails that were dropped by the transport service on the current day.

# --- Configuration ---
# Define the path for the output CSV file.
$OutputPath = "C:\Tools\oof_DROP.csv" # You can change this path

# --- Script ---

# Set the start and end times for the query to span the entire current day.
$startOfDay = (Get-Date).Date
$endOfDay = $startOfDay.AddDays(1).AddSeconds(-1)

Write-Host "Querying message tracking logs for dropped 'Automatic Reply' messages between $startOfDay and $endOfDay..."

# Query for dropped messages with "Automatische Antwort" in the subject, excluding the postmaster sender.
$droppedMessages = Get-TransportService | Get-MessageTrackingLog -wa 0 -EventId "DROP" -MessageSubject "Automatische Antwort" -Start $startOfDay -End $endOfDay | Where-Object { $_.Sender -ne 'postmaster@aps.local' }

if ($droppedMessages) {
    # Select the desired properties for both console output and CSV export.
    $outputData = $droppedMessages | Select-Object Timestamp, EventId, Source, Sender, @{Name='Recipients';Expression={$_.Recipients -join ';'}}, RecipientStatus, MessageSubject, InternalMessageId

    # Display the results in the console.
    Write-Host "Dropped 'Automatic Reply' messages found:"
    $outputData | Format-Table

    # Export the results to a CSV file, overwriting if it exists.
    Write-Host "Exporting results to $OutputPath..."
    $outputData | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8 -Force
    Write-Host "Export complete."
} else {
    Write-Host "No dropped 'Automatic Reply' messages found for the current day."
}