Home > OS >  Powershell - How to filter an attachment before download
Powershell - How to filter an attachment before download

Time:04-23

I am using a PowerShell script to download attachment from an email which has multiple attachment.

If I use below statement it will download all the attachments.

# Find Unread mail messages
$UnreadMessages = $Inbox.Items | where-object {$_.Unread -and $_.SenderEmailAddress -imatch "usa"}

I want to download only a specific attachment using below statement but it gives nothing.

# Find Unread mail messages
$UnreadMessages = $Inbox.Items | where-object {$_.Unread -and $_.SenderEmailAddress -imatch "usa" -and $_.Attachments -imatch "Backlog"}

Please help me correct this statement

CodePudding user response:

Firstly, your code will cause all Inbox messages to be downloaded and processed by your script. This is like a SELECT statement in SQL without a WHERE clause - as bad as it gets performance wise.

Use Items.Find/FindNext or Items.Restrict (see https://docs.microsoft.com/en-us/office/vba/api/outlook.items.find) - let the server/message store do the work. For your first query, use

@SQL=("urn:schemas:httpmail:read" = 0) AND ("http://schemas.microsoft.com/mapi/proptag/0x0065001F" like '%usa%')

For the second query, OOM won't let you search on the attachment name even though Extended MAPI (C or Delphi only) exposes that functionality (create RES_SUBRESTRICTION on PR_MESSAGE_ATTACHMENTS and specify PR_ATTACH_LONG_FILENAME as the search property). You can of course use only your first query and loop over the query matches, for each entry looping through each Attachment object in the MailItem.Attachments collection - far from ideal, but still better than no restriction at all.
If using Redemption (I am its author - it is an Extended MAPI wrapper and can be used from any language) is an option, it allows to use Attachments in queries. Something like the following (off the top of my head, VBA):

set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Folder = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
set restrItems = Folder.Items.Restrict(" (UnRead = 'true') AND (""http://schemas.microsoft.com/mapi/proptag/0x0065001F"" like '%usa%') AND (Attachments LIKE '           
  • Related