首页 > 解决方案 > FindItems() 在第一次运行时不起作用,但在第二次运行时起作用

问题描述

我正在尝试使用 PowerShell 从我的 Outlook Exchange 服务器邮箱中获取最新邮件。我已经看到最常见的解决方案是FindItems()在收件箱对象上做一个方法。但是,我发现第一次运行代码会引发错误说明

使用“1”参数调用“FindItems”的异常:“请求失败。

当我再次运行它时,脚本成功完成从我的邮箱返回最后一封邮件。为了说的更清楚,我写了一个脚本来执行循环FindItems()执行两次的方法,while如下图:

# bind to the Inbox folder of the target mailbox
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)

echo outsideWhile

$i = 0
while ($i -ne 2) {
    echo insideWhileBefore
    $inbox.FindItems(1)
    echo insideWhileAfter
    $i += 1
}

第一次执行$inbox.FindItems(1)失败,但第二次执行顺利返回所需的结果。

结果输出如下图

outsideWhile
insideWhileBefore
Exception calling "FindItems" with "1" argument(s): "The request failed. The remote server returned an error: (501)" ........
insideWhileAfter
insideWhileBefore
<MAIL CONTENTS>
insideWhileAfter

请帮助我了解为什么会发生这种情况以及如何克服它。

标签: powershellexchangewebservices

解决方案


推荐阅读