从特定Outlook文件夹中最近收到的电子邮件中获取文件

时间:2014-03-03 22:45:16

标签: powershell outlook etl

我想搜索特定的Outlook文件夹,查找最近发送的电子邮件,并将其附件保存到特定目录。

我编写了以下脚本,但它不起作用。有人可以建议需要改变什么才能起作用吗?

此外 - 在哪里可以找到我可以在PowerShell中使用的Outlook和Office特定方法和属性的列表?我尝试使用谷歌搜索,但无法找到它的官方MSDN页面。

#file path
$filepath = “C:\folder”
$account = "JonDoe@company.com"

#set outlook to open
$o = New-Object -comobject outlook.application
$n = $o.GetNamespace(“MAPI”)


$Account = $n.Folders | ? { $_.Name -eq $account };
    $f = $Account.Folders | ? { $_.Name -match 'FolderNameToSearch' };


$date = $f.Items| Select-Object -Property ReceivedTime | Sort-Object ReceivedTime -Descending | Select-Object -Index 0

#Write-Host $date


$f.Items | foreach 
{
   if ($_.ReceivedTime -match $date )
   {
        $_.attachments | foreach 
        {
            #Write-Host $_.filename
            $a = $_.filename
            $_.saveasfile((Join-Path $filepath $a))
        }
   }
}

编辑3/4/14 - 我逐步完成了脚本,我相信它在$_.ReceivedTime -match $date

失败了

我添加了以下代码来测试电子邮件ReceivedTime日期戳与$date存储的日期戳的值:

Write-Host "The date I am looking for is $date"

$f.Items | foreach {
   Write-Host $_.ReceivedTime
}

这是输出的一部分:

The date I am looking for is @{ReceivedTime=03/04/2014 03:16:08}
3/4/2014 3:16:08 AM

即使日期相同,数据类型也不同。将$date提升到日期时间的最优雅方式是什么,反之亦然?

1 个答案:

答案 0 :(得分:1)

首先,你太努力了。您正在循环浏览电子邮件两次以查找完全相同的电子邮件,这只是多余的。其次,Get-Date <DateTime Object/DateTime String>是你的朋友,但你甚至不需要它。如果你真的,真的,真的,真的想要对电子邮件进行排序,并选择第一个的日期/时间,然后根据我想你可以的那个日期/时间过滤它们,这就是你想要的:

if ((get-date $_.ReceivedTime) -eq (get-date $date))

我认为更好的解决方案将取代:

$date = $f.Items| Select-Object -Property ReceivedTime | Sort-Object ReceivedTime -Descending | Select-Object -Index 0

使用:

$email = $f.Items| Sort-Object ReceivedTime -Descending | Select-Object -First 1

然后你可以做以下事情:

Write-Output "Last email received at $($email.receivedtime), attached file(s) are: (if any)
$email.attachments|%{Write-Output $_.filename}

$email.attachments|%{$_.saveasfile((join-path $folder $_.filename))

我个人在那里添加If($email.attachments.count -gt 0){Do Stuff}else{Write-Output "Latest email at $($email.receivedtime) has no attachments!"}位。