Error while moving messages in Outlook using Powershell

0

I am trying to use Powershell to automate a task in Outlook. I want to output specific messages to a textfile, then move those selected messages to a new directory. Below is my concept code for this:

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

If I comment out the last two lines, the code works great. If I leave them in, I get the following error:

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
email
powershell
outlook
move
asked on Stack Overflow Mar 19, 2015 by user3038303 • edited Mar 19, 2015 by tchrist

2 Answers

0

Use the Find/FindNext or Restrict methods of the Items class to get the subset of items that correspond to the condition.

Also be aware, Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. See Considerations for server-side Automation of Office for more information.

answered on Stack Overflow Mar 19, 2015 by Eugene Astafiev
0

The error is RPC_S_CALL_FAILED which usually happens when Outlook closes when your code is running.

Also keep in mind that foreach cannot be used if you change the number of items in the collection by moving them. Use a down "for" loop from Items.Count down to 1.


User contributions licensed under CC BY-SA 3.0