使用Powershell从特定日期的Outlook下载.xlsx附件

问题描述

我有以下脚本。此$ Tests显示特定日期的.xlsx附件列表,但无法下载并引发错误。请找到以下脚本。

Add-type -assembly "Microsoft.Office.Interop.Outlook"
$olDefaultFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = New-Object -comobject outlook.application
$mapi = $outlook.GetNameSpace(“MAPI”)
$inBox = $mapi.GetDefaultFolder(6)
$FilePath= "c:\temp\Test\"
$subfolder = $inBox.Folders | Where-Object {$_.Name -eq “Test”}
$mail=$subfolder.Items |Select-Object -Property "ReceivedTime",@{name="Attachments";expression={$_.Attachments|%{$_.displayName}}} | Where-Object{$_.attachments -match ".xlsx" -and ($_.receivedtime -match "9/15/2020")} | Select-Object "attachments"
$Test = $mail.attachments
foreach ($out in $test) {$_.attachments|foreach {
Write-Host $_.filename
$Filename = $_.filename
If ($out.Contains("xlsx")) {
$_.saveasfile((Join-Path $FilePath "$out")) }}}

我能够过滤具有特定日期的.xlsx附件。但是之后,我不知道如何保存/下载它们。

解决方法

在Powershell中使用com对象可能会令人沮丧。我建议您对Get-Member非常熟悉。您确实必须询问每个对象。我已经简化了脚本并进行了全面测试。它将从每个匹配的电子邮件(接收日期)下载每个匹配的附件(名称)

Add-type -assembly "Microsoft.Office.Interop.Outlook"
$olDefaultFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = New-Object -comobject Outlook.Application
$mapi = $outlook.GetNameSpace(“MAPI”)
$inbox = $mapi.GetDefaultFolder(6)
$FilePath= "c:\temp\Test\"
$subfolder.Items | Where-Object {$_.receivedtime -match "9/20/2020" -and $($_.attachments).filename -match '.xlsx'} | foreach {
    $filename = $($_.attachments | where filename -match '.xlsx').filename
    foreach($file in $filename)
    {
        Write-Host Downloading $file to $filepath -ForegroundColor green
        $outpath = join-path $filepath $file
        $($_.attachments).saveasfile($outpath)
    }
}

您可以将其用于更多的“在线”方法。

Add-type -assembly "Microsoft.Office.Interop.Outlook"
$olDefaultFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = New-Object -comobject Outlook.Application
$mapi = $outlook.GetNameSpace(“MAPI”)
$inbox = $mapi.GetDefaultFolder(6)
$FilePath= "c:\temp\Test\"
$subfolder.Items | Where-Object {$_.receivedtime -match "9/20/2020" -and $($_.attachments).filename -match '.xlsx'} | foreach {
    foreach($attachment in $($_.attachments | where filename -match '.xlsx'))
    {
        Write-Host Downloading $attachment.filename to $filepath -ForegroundColor green
        $attachment.SaveAsFile((join-path $FilePath $attachment.filename))
        
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...