【O365 PowerShell Script】邮件跟踪报告

#O365有两种邮件跟踪报告:
#1.一种为快速报告(导出没有延迟),对应命令为get-messagetrace及get-messagetracedetail
#2.第二种为延迟细节报告(一般有1小时延迟,但是会更加细节),对应命令为get-historicalsearch

#以下脚本可以使用PowerShell导出比较直观的快速报告,和GUI相似,适合服务器运维定期导出报告使用

#O365 There are two types of mail tracking reports:
#1. One is for quick reports (no delay in export), and the corresponding commands are get-messagetrace and get-messagetracedetail
#2. The second type is the delayed detail report (usually there is a 1 hour delay, but it will be more detailed), and the corresponding command is get-historicalsearch

#The following script can use PowerShell to export more intuitive and fast reports, similar to GUI, suitable for server operation and maintenance to export reports regularly

#The below part needs to be modified
#以下部分需要更改
$startdate = 07/25/2020
$endDate = 07/26/2020
$CSV = "C:\Users\tonylin\AppData\Local\Microsoft\Outlook\test.csv"
#===============================================================================

#No need to modify below parts
#以下部分无需更改
$results = @()

$page = 1

While (get-messagetrace -StartDate $startdate -EndDate $endDate -pagesize 5000 -page $page) 
{
    $MessageTrace = get-messagetrace -StartDate $startdate -EndDate $endDate -pagesize 5000 -page $page
    $page++

    foreach($Trace in $MessageTrace)
    {
        $MessageDetail = get-messagetracedetail -MessageTraceId $Trace.messagetraceid.guid -recipientaddress $trace.recipientaddress

        foreach($detail in $MessageDetail)
        {
            $data = (($detail.data).split("/><") | where-object {$_ -like "*return*"})
            if($data)
            {

                $return_path = $data.split(‘"‘)[3]

                if($return_path -eq "<>")
                {
                    $return_path = "<>"
                }
            }else{
                $return_path = ""
            }

            $results += New-Object PSObject -property @{ 
                    MessageId = $detail.messageid
                    Date = $detail.Date
                    Event = $detail.Event
                    Action = $detail.Action
                    Detail = $detail.Detail
                    Data = $detail.Data
                    SenderAddress = $Trace.senderaddress
                    RecipientAddress = $Trace.RecipientAddress
                    ReturnPath = $return_path
                    }
        }
    }
}

$results |select MessageId,Date,Event,Action,Detail,Data,SenderAddress,RecipientAddress,ReturnPath | export-csv $CSV -notypeinformation -encoding utf8

相关推荐