Search code examples
emailpowershellcomoutlookpowershell-4.0

Can't make selection (can't filter) of collection while processing e-mails


I want to create some automation of e-mail processing.

I followed this article and it worked fine. Summary, I got a collection of e-mails of one of my mailbox, however I can't filter them (can't provide where method). I can use foreach operator, but it seems to me it's not a best idea (like using cursor functionality in order to filter tables value in SQL instead of using 'where' option).

Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -comobject Outlook.Application
$namespace = $Outlook.GetNameSpace("MAPI")

$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)

$mailsInEventFolder = $inbox.Folders.Item('Events').Items

By implementing the last command I'm getting collection of my e-mails (collection of System.MarshalByRefObject). Common methods for common collection like where{$_ -eq ...} are not working here.

If I try where method, I'm getting an error message "MethodNotFound". Also I can't get list of all methods for this collection by using Get-Member command, because it gives me methods of e-mail object and I need methods of collection-object.

I know that for this collection I can use the following:

  • $mailsInEventFolder.Item(int32)
  • $mailsInEventFolder.Item(string)
  • $mailsInEventFolder.Count
  • $mailsInEventFolder.Add(obj)
  • $mailsInEventFolder.Remove(int32)

I wasted a lot of time while searching this correct object collection in documentation, however I didn't succeed.

Please give me advice how to filter my e-mail by value of some property of e-mail object without using foreach. Or please give me correct reference to description of this collection object.


Solution

  • You need to use Items.Find/FindNext or Items.Restrict. Do not loop through the items in a folder looking for a match (that is what you code does) - each item will need to be opened. Let the store provider do the heavy lifting.