powershell - Outlook PowerShell 脚本无法检索最新电子邮件

标签 powershell outlook etl

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

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

是否有某种方法可以在脚本提示扫描之前提示 Outlook 刷新?

我的代码如下:

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

<#
#file path
$filepath = "I:\folder"
$account = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebcbcb0aab1ab9fb7b0acabf1bcb0b2" rel="noreferrer noopener nofollow">[email protected]</a>" 
#>

#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!"
}

最佳答案

听起来你需要一个

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

在那里确保如果处于缓存模式,它将在检查电子邮件之前发送和接收。请参阅下面的编辑注释。

您可能还想通过以下方式确保用户未处于离线模式:

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

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

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

关于powershell - Outlook PowerShell 脚本无法检索最新电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23342421/

相关文章:

powershell - Windows 终端 - 使用不同的配置文件启动 powershell

HTML 时事通讯 - 不同版本的 Outlook 修复

sql-server - 如何在 SSIS 脚本组件中按名称循环遍历列?

cassandra - 导入 Cassandra - 使用 python UDF 和 CqlStorage 传递列表对象

powershell - PowerShell 是否要求脚本 block 的左花括号在同一行上?

powershell - 使用Powershell获取HDD序列号

c# - 创建 .ICS 文件,添加到 Outlook

javascript - 使用来自 IE 网站的 html 正文在 outlook 中打开新电子邮件

multithreading - Node.js 数据处理分布

powershell - 无法在递归复制期间排除文件夹