Skip to content

Instantly share code, notes, and snippets.

@stelf
Last active July 19, 2021 09:37
Show Gist options
  • Save stelf/e8ba5a569634afd8c60263fe84d49470 to your computer and use it in GitHub Desktop.
Save stelf/e8ba5a569634afd8c60263fe84d49470 to your computer and use it in GitHub Desktop.
iterate outlook folder item search results via powershell COM automation
# this GIST is available under the conditions of
# https://creativecommons.org/licenses/by/4.0/
# example how to search Outlook mailbox via COM automation
# + find lines with specific text while also further filtering these
# this approach is actually much more readable than the VB examples in MS help
# thanks to escaped quotes not subject to some ugly concatenation practices
#
# useful references here:
# https://docs.microsoft.com/en-us/office/vba/outlook/how-to/search-and-filter/filter-the-body-of-a-mail-item
# https://stackoverflow.com/questions/44881641/outlook-advanced-search-urnschemashttpmaildatereceived
# https://docs.microsoft.com/en-us/office/vba/api/outlook.application.advancedsearch
#
# get COM object
$otl = New-Object -ComObject Outlook.Application
# list of available MAPI stores - useful for figuring FolderPath for search query
$otl.GetNamespace('MAPI').Folders | select Name
# list of Folders in the first store (is again called Folder)
$otl.GetNamespace('MAPI').Folders[1].Folders | select Name
# prepare filter to look for mails with ALTER and TABLE (two conditions in conjunction)
# the urn:schemas:httpmail:textdescription thing denotes the body of the message 🤦🏽‍♀️
$filt = $otl.AdvancedSearch(
"'\\mailbox\Folder'",
"(urn:schemas:httpmail:textdescription like '%ALTER%') and (urn:schemas:httpmail:textdescription like '%TABLE%')")
# filter ouit certain lines from the body
$filt.Results | Select Body | Select-String 'ALTER.*' | %{$_.Matches.Value }
#or with sender name...
$filt.Results | Select-Object -Property `
@{label='Sender'; expression = {$_.Sender.Name}},
@{label='SQL'; expression = {$_.Body | Select-String 'ALTER.*' | %{$_.Matches.Value }}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment