如何在 24 小时内根据特定文件名下载 Outlook 附件?

How to download an Outlook attachments based on specific file name within the 24 hrs?

我正在尝试根据过去 24 小时内收到的文件名下载电子邮件中的附件,这些文件名是第一个匹配项。第一个匹配项是为了防止收到第二封具有相同文件名的电子邮件,并且需要将其输出到该位置。这些文件通常每天一次收到收件箱,但有时必须通过 'latest received' 处理。所以机智地说,当有匹配时,代码应该抓取文件并将第一个匹配的文件放到该位置,然后停止/终止脚本。

然而,它似乎根本没有考虑时间因素。此时我的代码根据文件名找到第一个匹配的两个文件,并将它们转储到该位置。然后它不断覆盖文件,因为它在收件箱中找到具有相同名称的旧文件。

在这个最新的构建/尝试中,我在代码中使用了 $limit = (Get-Date).AddDays(-1)-and ($_.CreationTime -lt $limit)。我尝试了很多方法,但似乎没有任何效果。

    $account = 'blah@stihlse.com'
    $targetFolder = 'inbox'
    $f = $account.Folders | ? { $_.Name -match 'inbox'};
    $email = $f.Items|  Sort-Object ReceivedTime -Descending | Select-Object -First 1 
    $limit = (Get-Date).AddDays(-1)
    $filepath = "\servername\home\blah\Documents\blah's emails"
    $ol = New-Object -comobject outlook.application
    $ns = $ol.GetNamespace('MAPI')
    $acct = $ns.Folders[$account]
$acct.Folders[$targetFolder].Items | foreach {
    if ($_.ReceivedTime -match $email -and ($_.CreationTime -eq $limit)) { 
            $_.attachments |
            foreach {
                Write-Host "attached file: ",$_.filename
                If ($_.filename -match 'BlahCompletions' -or $_.filename -match 'BlahCertifications'){
                    $_.saveasfile((Join-Path $filepath $_.FileName))
                } 
            } 
    }
}

您使用CreationTime -eq $limit-eq表示相等。所以它只有在 CreationTime$limit 完全相同的微秒时才有效。您要查找的是 -gt(大于)或 -ge(大于或等于)。

另一个问题是$_.ReceivedTime -match $email。它正在尝试 -matchReceivedTime 转换为正则表达式。但是你提供的正则表达式是整个$email。看看about_Comparison_Operators

在您迭代文件夹中所有项目的代码中:

$acct.Folders[$targetFolder].Items | foreach {
    if ($_.ReceivedTime -match $email -and ($_.CreationTime -eq $limit)) { 

如果文件夹中有大量项目,这确实不是一个好主意。相反,您需要使用 Items class 的 Find/FindNext or Restrict 方法。在以下文章中阅读有关这些方法的更多信息:

例如,要仅获取带有附件的物品,您可以使用以下条件:

query ="@SQL=" & chr(34) & "urn:schemas:httpmail:hasattachment" & chr(34) & "=1"