Skip to main content

Finding RMS Items in a Mailbox using EWS

If you want to search for emails that have been protected using AD Rights Managed Service using EWS there are a few challenges. How RMS works with Email it is documented in the following Exchange Protocol document https://msdn.microsoft.com/en-us/library/cc463909(v=exchg.80).aspx. The important part when it comes to searching is PidNameContentClass property https://msdn.microsoft.com/en-us/library/office/cc839681.aspx which on RMS messages gets set to rpmsg.message. So to search for this Internet Header you can use a SearchFilter like the following to define the ExtendProperty to search folder

$contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
$sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 

Putting it together in a script that searches a Folder in a Mailbox based on a MailboxName and FolderPath This script is on GitHub https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1  (An important point to note while you can find email that has been protected using RMS with EWS you won't be able to read the encrypted contents using EWS).

function Get-RMSItems{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$true)] [String]$FolderPath

 )
 begin
 {
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $Folder = Get-FolderFromPath -FolderPath $FolderPath -MailboxName $MailboxName -service $service 
  $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
  #Define ItemView to retrive just 1000 Items    
  $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-Output $Item
      }    
      $ivItemView.Offset += $fiItems.Items.Count    
  }while($fiItems.MoreAvailable -eq $true)  
 
 }
}

function Get-FolderFromPath{
 param (
   [Parameter(Position=0, Mandatory=$true)] [string]$FolderPath,
   [Parameter(Position=1, Mandatory=$true)] [string]$MailboxName,
   [Parameter(Position=2, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=3, Mandatory=$false)] [Microsoft.Exchange.WebServices.Data.PropertySet]$PropertySet
    )
 process{
  ## Find and Bind to Folder based on Path  
  #Define the path to search should be seperated with \  
  #Bind to the MSGFolder Root  
  $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)   
  $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  #Split the Search path into an array  
  $fldArray = $FolderPath.Split("\") 
   #Loop through the Split Array and do a Search for each level of folder 
  for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
         #Perform search based on the displayname of each folder level 
         $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
   if(![string]::IsNullOrEmpty($PropertySet)){
    $fvFolderView.PropertySet = $PropertySet
   }
         $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
         $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
         if ($findFolderResults.TotalCount -gt 0){ 
             foreach($folder in $findFolderResults.Folders){ 
                 $tfTargetFolder = $folder                
             } 
         } 
         else{ 
             Write-host ("Error Folder Not Found check path and try again")  
             $tfTargetFolder = $null  
             break  
         }     
     }  
  if($tfTargetFolder -ne $null){
   return [Microsoft.Exchange.WebServices.Data.Folder]$tfTargetFolder
  }
  else{
   throw ("Folder Not found")
  }
 }
}

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
}

One last sample that does a statistics report of all RMS items in a Mailbox using a SearchFilter on the AllItems Search Folder (which is created by the Outlook Desktop client) this outputs a report of the RMS Items and the size of those item in each folder that looks like


This script is on GitHub at https://github.com/gscales/Powershell-Scripts/blob/master/GetRMSItems.ps1

function ConvertToString($ipInputString){  
    $Val1Text = ""  
    for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){  
            $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))  
            $clInt++  
    }  
    return $Val1Text  
} 

function Get-RMSItems-AllItemSearch{
    param
 ( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials

 )
 begin
 {
  $FolderCache = @{}
  $service = connect-exchange -Mailbox $MailboxName -Credentials $Credentials
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)  
  $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  GetFolderPaths -FolderCache $FolderCache -service $service -rootFolderId $MsgRoot.Id
  $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);
  $folderidcnt = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)
  $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
  $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Shallow;
  $sf1 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"2")
  $sf2 = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"allitems")
  $sfSearchFilterCol = new-object  Microsoft.Exchange.WebServices.Data.SearchFilter+SearchFilterCollection([Microsoft.Exchange.WebServices.Data.LogicalOperator]::And)
  $sfSearchFilterCol.Add($sf1)
  $sfSearchFilterCol.Add($sf2)
  $fiResult = $Service.FindFolders($folderidcnt,$sfSearchFilterCol,$fvFolderView)
  $fiItems = $null
  $RptCollection = @{}
  $ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
  if($fiResult.Folders.Count -eq 1)
  {
   $Folder = $fiResult.Folders[0]
      $contentclassIh = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::InternetHeaders,"content-class",[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
   $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($contentclassIh,"rpmsg.message") 
   #Define ItemView to retrive just 1000 Items    
   $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){     
     if($FolderCache.ContainsKey($Item.ParentFolderId.UniqueId))
     {
      if($RptCollection.ContainsKey($FolderCache[$Item.ParentFolderId.UniqueId]))
      {
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalItems++
       $RptCollection[$FolderCache[$Item.ParentFolderId.UniqueId]].TotalSize+= $Item.Size
      }
      else
      {
       $fldRptobj = "" | Select FolderName,TotalItems,TotalSize
       $fldRptobj.FolderName = $FolderCache[$Item.ParentFolderId.UniqueId]
       $fldRptobj.TotalItems = 1
       $fldRptobj.TotalSize = $Item.Size 
       $RptCollection.Add($fldRptobj.FolderName,$fldRptobj)
      }     
     }
       }    
       $ivItemView.Offset += $fiItems.Items.Count    
   }while($fiItems.MoreAvailable -eq $true)    
   
  }
  write-output $RptCollection.Values
 }
 

}

function GetFolderPaths
{
 param (
      [Parameter(Position=0, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.FolderId]$rootFolderId,
   [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service,
   [Parameter(Position=2, Mandatory=$true)] [PSObject]$FolderCache,
   [Parameter(Position=3, Mandatory=$false)] [String]$FolderPrefix
    )
 process{
 #Define Extended properties  
 $PR_FOLDER_TYPE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(13825,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
 $PR_MESSAGE_SIZE_EXTENDED = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3592, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Long);
 #Define the FolderView used for Export should not be any larger then 1000 folders due to throttling  
 $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)  
 #Deep Transval will ensure all folders in the search path are returned  
 $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;  
 $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
 $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
 #Add Properties to the  Property Set  
 $psPropertySet.Add($PR_Folder_Path);  
 $psPropertySet.Add($PR_MESSAGE_SIZE_EXTENDED)
 $fvFolderView.PropertySet = $psPropertySet;  
 #The Search filter will exclude any Search Folders  
 $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PR_FOLDER_TYPE,"1")  
 $fiResult = $null  
 #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox  
 do 
 {  
     $fiResult = $service.FindFolders($rootFolderId,$sfSearchFilter,$fvFolderView)  
     foreach($ffFolder in $fiResult.Folders){
         #Try to get the FolderPath Value and then covert it to a usable String 
   $foldpathval = $null
         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))  
         {  
             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)  
             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }  
             $hexString = $hexArr -join ''  
             $hexString = $hexString.Replace("FEFF", "5C00")  
             $fpath = ConvertToString($hexString)  
         }
   if($FolderCache.ContainsKey($ffFolder.Id.UniqueId) -eq $false)
   {
    if ([string]::IsNullOrEmpty($FolderPrefix)){
     $FolderCache.Add($ffFolder.Id.UniqueId,($fpath)) 
    }
    else
    {
     $FolderCache.Add($ffFolder.Id.UniqueId,("\" + $FolderPrefix + $fpath)) 
    }
   }
     } 
     $fvFolderView.Offset += $fiResult.Folders.Count
 }while($fiResult.MoreAvailable -eq $true)  
 }
}


Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to access and restore deleted Items (Recoverable Items) in the Exchange Online Mailbox dumpster with the Microsoft Graph API and PowerShell

As the information on how to do this would cover multiple posts, I've bound this into a series of mini post docs in my GitHub Repo to try and make this subject a little easier to understand and hopefully navigate for most people.   The Binder index is  https://gscales.github.io/Graph-Powershell-101-Binder/   The topics covered are How you can access the Recoverable Items Folders (and get the size of these folders)  How you can access and search for items in the Deletions and Purges Folders and also how you can Export an item to an Eml from that folder How you can Restore a Deleted Item back to the folder it was deleted from (using the Last Active Parent FolderId) and the sample script is located  https://github.com/gscales/Powershell-Scripts/blob/master/Graph101/Dumpster.ps1

Using the MSAL (Microsoft Authentication Library) in EWS with Office365

Last July Microsoft announced here they would be disabling basic authentication in EWS on October 13 2020 which is now a little over a year away. Given the amount of time that has passed since the announcement any line of business applications or third party applications that you use that had been using Basic authentication should have been modified or upgraded to support using oAuth. If this isn't the case the time to take action is now. When you need to migrate a .NET app or script you have using EWS and basic Authentication you have two Authentication libraries you can choose from ADAL - Azure AD Authentication Library (uses the v1 Azure AD Endpoint) MSAL - Microsoft Authentication Library (uses the v2 Microsoft Identity Platform Endpoint) the most common library you will come across in use is the ADAL libraries because its been around the longest, has good support across a number of languages and allows complex authentications scenarios with support for SAML etc. The
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.