Search code examples
powershelloutlookoffice-interopoutlook-2007mapi

Outlook Items.Restrict Does not return all messages


I have a small powershell script, which uses Outlook interop to move certain messages from inbox to other folders. The basic move operation is done using the code below:

[Reflection.Assembly]::LoadWithPartialname("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)
$filter = "[SenderName] = 'Dummy Sender'"
$messages = $inbox.items.Restrict($filter)
$messages | % { 
    Write-Host "`t$($_.Subject)" 
    [void]$_.Move($destination) | Out-Null
}

The problem I'm noticing is that items.Restrict is not returning all matching messages. Each time I run the script, I get anywhere from 3 to 20 messages.

Has anyone observed this behavior before? Is there something obvious that I'm missing?


Solution

  • You are modifying the collection while you are still in the loop. either save the entry ids into a static array/list and then reopen the messages one at a time or use a loop from count down to 1.