Skip to main content

Using the ExcludesBitmask SearchFilter\ Restriction in EWS

Complex properties are one of the more challenging elements when it comes to developing with Exchange and bitwise properties are one of the more challenging property types you may need to deal with. The most common bitwise property in Exchange you may access/use is the PR_MessageFlags property https://msdn.microsoft.com/en-us/library/ee160304(v=exchg.80).aspx . If you look at this property on a Message that you received you might see something like


What the  ExcludesBitmask SearchFilter/Restriction in EWS allows you to do is create a search where you can specifically exclude messages because they have one of these bitmask values set. Eg you might want to exclude Draft messages from your search or maybe you want to exclude any messages that where SentBy you in the Inbox. You can also use this Search Filter with the Not filter which Negates the restriction so if I created a Searchfilter to excluded all messages with the MSGFlag_HasAttached then negated that with the Not filter I would then only get the message where the MSGFlag_HasAttached bit-wise is set.

Using this the EWS Managed API is pretty simple you first define the property you want to search on and then create a SearchFilter using this property and the Bitwise Value as the variable eg

ExtendedPropertyDefinition PR_MESSAGE_FLAGS = new ExtendedPropertyDefinition(0x0E07,MapiPropertyType.Integer);
SearchFilter ExcludeDraft = new SearchFilter.ExcludesBitmask(PR_MESSAGE_FLAGS, 8);

This creates a SearchFilter that excludes draft messages, If you want to Negate that you can use

SearchFilter JustDrafts = new SearchFilter.Not(ExcludeDraft);

Which would then create a filter that just retrieved draft messages.

In PowerShell you can write a function like the following

function Query-MessageFlag  {
     param( 
             [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [switch]$useImpersonation,
  [Parameter(Position=3, Mandatory=$false)] [string]$url,
                [Parameter(Position=4, Mandatory=$true)] [Int32]$Flag,
  [Parameter(Position=5, Mandatory=$true)] [string]$FolderPath,
  [Parameter(Position=6, Mandatory=$false)] [switch]$Negate,
  [Parameter(Position=7, Mandatory=$false)] [switch]$SummaryOnly
    )  
  Begin
 {
  if($url){
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials -url $url 
  }
  else{
   $service = Connect-Exchange -MailboxName $MailboxName -Credentials $Credentials
  }
  if($useImpersonation.IsPresent){
   $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  }
   $folderId = FolderIdFromPath -FolderPath $FolderPath -SmtpAddress $MailboxName
  if($folderId -ne $null){
   $Folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderId) 
   Write-Host ("Folder Name : " + $Folder.DisplayName)
   $PR_MESSAGE_FLAGS = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E07,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer); 
   $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+ExcludesBitmask($PR_MESSAGE_FLAGS, $Flag) 
                        if($Negate.IsPresent){
    $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Not($sfItemSearchFilter)
   }   
   if(!$SummaryOnly.IsPresent){
    $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
    $fiItems = $null    
    do{    
     $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)    
     #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)  
     foreach($Item in $fiItems.Items){      
         Write-Host($Item.DateTimeReceived.ToString() + " : " + $Item.Subject)       
     }    
     $ivItemView.Offset += $fiItems.Items.Count    
    }while($fiItems.MoreAvailable -eq $true) 
   }
   else
   {
     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)
     $fiItems = $service.FindItems($Folder.Id,$sfItemSearchFilter,$ivItemView)  
     Write-Host ("Total Items : " + $fiItems.TotalCount)
   }
  }
 }
}

The above function comes from the following script on Github https://github.com/gscales/Powershell-Scripts/blob/master/ExcludeQuery.ps1 demonstrates how to either get Items or a Summary count of those Items based on a bitwise flag exclusion or a negation of that exclusion. Again some examples may be in order

Example 1 Search for messages in the Inbox not sent from you using the mfFromMe bitwise flag

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 32 -SummaryOnly

Example 2 Search for messages in the Inbox  sent from you using the mfFromMe bitwise flag (this is using a Negate filter)

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 32 -SummaryOnly -Negate

Example 3 Search for messages with the Attach Flag set in the Inbox mfHasAttach

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 16 -SummaryOnly -Negate

Example 4 Search for message with Read Recipient flag mfNotifyRead and Negate that

Query-MessageFlag -MailboxName user@domain.com -FolderPath '\Inbox' -Flag 256  -SummaryOnly -Negate

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is. I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned) #Define Date to Query $StartDate = (Get-Date) $EndDate

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script. So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this

EWS Managed API and Powershell How-To series Part 1

I thought I'd start the year with a series of posts that goes back over the basics of using the EWS Managed API from Powershell and provides a modular remarked example that you can easily cut and paste to build your own scripts. Along the way in this series I'll show a whole bunch of examples around specific things. As a starting point for versions this will be Powershell Version 2.0  and the EWS Managed API 1.1 (which will soon change to 1.2 once released) http://www.microsoft.com/download/en/details.aspx?id=13480. The starting point for any EWS script your going to write is connecting to Exchange for which there are three important pieces of information you will need. Firstly you need to know the version of Exchange your running in this script its going to be held in the following variable $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1 Other valid values for Exchange 2007 would be $ExchangeVersion = [Microsoft.Exchange.Web
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.