首页 > 解决方案 > Powershell中的Outlook电子邮件ReceivedTime乱序

问题描述

长期潜伏者和首次发布者,所以我会在这里尽可能具体!

我正在编写的脚本的目标是从 excel 文件中获取开始和结束日期,并使用该范围从 Outlook 中提取该范围内的最新电子邮件。然后使用这些电子邮件中的信息在电子表格中制​​作报告。

该脚本按预期工作,除了某些日期的 ReceivedTime 属性出现故障并且它最终获取最早的可能条目而不是最新的条目。

如果我$Emails.ReceivedTime在控制台中输入,它会乱序显示导致问题的它们。如果我输入$Emails.ReceivedTime | sort,问题就会消失。我的问题是,无论我在哪里尝试将它插入我的脚本,它都会挂起并且永远不会完成执行。

Function GetEmails ()
{
    Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
    $Outlook = New-Object -ComObject Outlook.Application
    $Namespace = $Outlook.GetNameSpace("MAPI")
    $Inbox = $Namespace.Folders.Item('UsernameHere').Folders.Item('Inbox').Items
    return $Inbox
}

Function GetXYZ($Emails) {

    $XYZ = $null
    foreach($Email in $Emails) {   
        if ($Email.SenderEmailAddress -ne $null -and $Email.SenderEmailAddress.Contains('xyz@123.com')) {  
            if (($Email.ReceivedTime -le $end_date) -and ($Email.ReceivedTime -ge $start_date)) {  

                $XYZ = New-Object psobject -Property @{'Sender' = $Email.SenderEmailAddress; 'Time' = $Email.ReceivedTime; 'Body' = $Email.Body}                  
            }

        }
    }

    #Split the body of the email into an array and remove whitespace from the array.
    $Array = $XYZ.Body.Split("`r`n",[System.StringSplitOptions]::RemoveEmptyEntries)

    #Create an array of numeric values only
    $numArray = @()
    $numArray += $Array -replace '[^.0-9]'

    $junk1, [int]$Item1, [int]Item2, [int]$Item3, $junk2 = $numArray

    return New-Object psobject -Property @{'Name' = 'XYZ'; 'Time' = $XYZ.Time; 'Item1' = $Item1.toString("N0"); 'Item2' = $Item2.toString("N0"); 'Item3' = $Item3.toString("N0")}
}


$Emails = GetEmails

GetXYZ($Emails)

#Rest of the code runs here to do things unrelated to my problem...

这是当前收到的前 10 封电子邮件:

2019 年 5 月 23 日星期四上午 7:22:19

2019 年 5 月 23 日星期四上午 6:55:07

2019 年 5 月 23 日星期四上午 6:22:18

2019 年 5 月 23 日星期四上午 6:03:07

2019 年 5 月 23 日星期四上午 6:02:21

2019 年 5 月 23 日星期四上午 5:22:17

2019 年 5 月 23 日星期四凌晨 4:22:03

2019 年 5 月 23 日星期四凌晨 3:55:07

2019 年 5 月 23 日星期四凌晨 3:22:18

2019 年 5 月 23 日星期四凌晨 3:01:33

这是前 10 行应该是:

2019 年 4 月 3 日星期三上午 9:00:07

2019 年 4 月 4 日星期四上午 9:00:04

2019 年 4 月 5 日星期五上午 9:00:08

2019 年 4 月 6 日星期六 5:03:22

2019 年 4 月 6 日星期六上午 5 点 11 分 22 秒

2019 年 4 月 6 日星期六上午 5 点 22 分 29 秒

2019 年 4 月 6 日星期六 7:08:59

2019 年 4 月 6 日星期六 8:11:08

2019 年 4 月 6 日星期六上午 8 点 55 分 45 秒

2019 年 4 月 6 日星期六上午 9:00:02

如果我在这里遗漏了任何重要的内容,请随时告诉我,并提前感谢!

标签: powershelloutlook

解决方案


遍历文件夹中的所有项目并不是一个好主意:

 foreach($Email in $Emails) 

相反,我建议获取一小部分项目进行处理(一堆)。例如,您可以提取每周或每月的项目等。如果集合中有少量 Outlook 项目,我建议使用Findand方法(请参阅 Items.Count 属性)。FindNext另一方面,如果集合中有大量项目并且预计只能找到少数项目,则该Restrict方法比Find/方法工作得更快。FindNext

在以下文章中阅读有关这些方法的更多信息:


推荐阅读