代码之家  ›  专栏  ›  技术社区  ›  Alex

Powershell按标题搜索Outlook电子邮件并提取最新的Excel(.xls)文件

  •  0
  • Alex  · 技术社区  · 8 年前

    我是一家考试机构的实习生。 我正在尝试自动化一项很长的任务,我正在使用Powershell来完成大部分工作。

    任务: 我们有一封公司电子邮件,白天收到很多电子邮件。当然,我们制定了一些规则,让我们的生活更容易忍受。 每天都有特定的电子邮件发送到文件夹“XYZ”,我想使用以下条件搜索最新的电子邮件: -电子邮件标题 -包含搜索字符串的最新电子邮件

    每封电子邮件都包含一个Excel文件。如果正文标题与搜索条件匹配,我想下载最新的附件。除非有办法在不下载的情况下打开并解析文件。

    我对Powershell非常陌生,但我有编程背景,所以不要为了简化自己而退缩。

    顺致敬意, 亚历克斯

    1 回复  |  直到 8 年前
        1
  •  4
  •   colsw    8 年前

    您需要自己完成大部分工作,但这是来自我的一个类似脚本的代码,我已经对其进行了分解,以使其更具可读性,希望您能够开始。

    #Params
    $Account = "Mailbox.Searchme@contoso.com"
    $Folder = "Inbox"
    $SubjMatch = "Reports"
    
    #Create outlook COM object to search folders
    $Outlook = New-Object -ComObject Outlook.Application
    $OutlookNS = $Outlook.GetNamespace("MAPI")
    
    #Get all emails from specific account and folder
    $AllEmails = $OutlookNS.Folders.Item($Account).Folders.Item($Folder).Items
    #Filter to emails with attatchments and specific subject line (-match uses RegEx)
    $ReportsEmails = $AllEmails | ? { ($_.Subject -match $SubjMatch) -and ($_.Attachements.Count -gt 0) }
    #Grab the most recently recieved email
    $LatestReportEmail = $ReportsEmails | Sort ReceivedTime | Select -Last 1
    
    #Get the xlsx file(s) and save them
    $LatestReportEmail.Attachments | ? {$_.FileName -match "\.xlsx$"} | % {
        $_.SaveAsFile("C:\path\to\$($_.FileName)")
    }
    
    #Quit Outlook COM Object
    $Outlook.Quit()
    

    在尝试运行此操作之前,您应该关闭Outlook,而且在大文件夹上运行此操作可能会非常慢(由于某些原因,主要是筛选部分),祝您好运。