Powershell - 根据主题匹配将 Outlook 项目从收件箱移动到子文件夹

Powershell - Moving outlook items from inbox to subfolder based on subject match

我是 powershell 的新手,我正在尝试编写一个脚本,如果电子邮件主题与字符串匹配,该脚本会将项目从 outlook 收件箱移动到 'Test' 子文件夹中。该脚本通常可以正常工作,但会跳过一些电子邮件。

我第一次 运行 它移动了 4 封与字符串匹配的电子邮件中的 2 封。 第二次我 运行 它,它移动了第三封电子邮件。 第 3 次我 运行 它,它移动了第 4 封电子邮件。

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $inbox.Folders | where-object { $_.name -eq "Test" }
$inbox.items | ForEach {
    $a=$_.subject -like 'Test*'
    if ($a) {[void]$_.Move($targetFolder)
    }
}

我不明白为什么它不会在我第一次执行时移动所有主题与 'Test*' 字符串匹配的电子邮件。

如有任何帮助,我们将不胜感激! 谢谢

我在通过 Outlook.Application 访问 Outlook 收件箱时看到的唯一警告是 Outlook 通常是在 cached mode 中设置的。 根据经验,不会枚举 Outlook 缓存之外的电子邮件。

编辑:似乎也记录了此行为 - 来自 Managing an Outlook mailbox with powershell

Experience shows that merely looping through all the messages in the Sent Items folder once isn’t enough; on a first loop, some items are handled but others aren’t touched. It may take three or four such loops to handle all the items that need handling. The number of loops probably depends on how many mail items are ready for copy-move operations and other factors in how Outlook interoperates with your computer. In any event, the solution is to use a Do-While structure to keep running the loop until all marked items have been properly managed.