Outlook PowerShell脚本不会检索最新的电子邮件

时间:2014-04-28 13:28:46

标签: powershell outlook etl

我有一个脚本,可以读取电子邮件的Outlook文件夹,选择最近收到的电子邮件,并将其附件保存到目录中。

它无法正常工作 - 如果我在运行脚本之前首先打开Outlook,它似乎只知道接收哪个电子邮件 - 否则,它认为最近收到的电子邮件是我最后收到的电子邮件Outlook最后打开了。

在脚本提示扫描之前,有没有办法提示Outlook刷新?

我的代码如下:

$filepath = $args[0]
$account = $args[1]

<#
#file path
$filepath = "I:\folder"
$account = "account@host.com" 
#>

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

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

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

# Log the email we are looking for, and mention attachments if they exist.
Write-Output "Last email received at $($email.receivedtime), attached file(s) are: (if any)"
$email.attachments | %{Write-Output $_.filename}

# If the email has at least one attachment, save them to the filepath.
if ($email.attachments.count -gt 0) {
    $email.attachments | %{$_.saveasfile((join-path $filepath $_.filename))} 
} else { 
    Write-Output "Latest email at $($email.receivedtime) has no attachments!"
}

2 个答案:

答案 0 :(得分:3)

听起来你需要一个

$a.Store | ?{$_.DisplayName -eq $account} | %{If($_.IsCachedExchange){Start-Job {$n.SendAndReceive($false)}|Wait-Job}}

在那里确保如果它处于缓存模式,它将发送&amp;在检查电子邮件之前收到。请参阅下面的编辑说明。

您可能还希望确保用户未处于离线模式,并使用:

If($n.offline){write-host "You must be online before performing this script" -fore red;start-sleep 5;break}

这样,如果用户处于离线模式,它将显示红色文字,表明他们需要处于在线模式,等待5秒,然后退出脚本。

修改:感谢Adi Inbar,它将等待Outlook完成其发送和接收过程,然后再继续确保您在继续之前缓存了最新的电子邮件。谢谢阿迪,我不知道那个命令,它非常方便!

答案 1 :(得分:1)

这是一个缓存(而不是在线)Exchange商店吗?尝试关闭缓存。

相关问题