使用Powershell在Outlook中移动邮件时出错

时间:2015-03-19 13:58:08

标签: email powershell outlook move

我正在尝试使用Powershell在Outlook中自动执行任务。我想将特定消息输出到文本文件,然后将这些选定的消息移动到新目录。以下是我的概念代码:

Add-type -assembly "Microsoft.Office.Interop.outlook" | out-null
$olfolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$inbox = $namespace.getDefaultFolder($olFolders::olFolderInBox)

$ProcessedFolder = $inbox.folders.Item('Cyber').items

$DateVar = get-date -Format yyyyMMdd
$OutputFile2 = "C:\temp\Cyberemaildump" + $DateVar + ".txt"
$messages = $inbox.Items | ? {$_.SenderName -match "Cyber"} > $OutputFile2
foreach($message in $messages){$message.move($ProcessedFolder)}

$ProcessedFolder | Group-Object -Property SenderName -NoElement |Sort-Object count

如果我注释掉最后两行,代码效果很好。如果我留下它们,我会收到以下错误:

The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
Outlookautomation.ps1:21 char:1
+ $messages = $inbox.Items | ? {$_.SenderName -match "Cyber"} > $OutputFile2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

2 个答案:

答案 0 :(得分:0)

使用Items类的Find / FindNextRestrict方法获取与条件对应的项的子集。

另请注意,Microsoft目前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括ASP,ASP.NET,DCOM和NT服务)自动化Microsoft Office应用程序,因为在此环境中运行Office时,Office可能会出现不稳定的行为和/或死锁。有关详细信息,请参阅Considerations for server-side Automation of Office

答案 1 :(得分:0)

错误是RPC_S_CALL_FAILED,通常在代码运行时Outlook关闭时发生。

另请注意,如果通过移动它们来更改集合中的项目数,则不能使用foreach。使用向下"用于"从Items.Count循环到1。