Quantcast
Channel: Glen's Exchange and Office 365 Dev Blog
Viewing all articles
Browse latest Browse all 241

Searching based on Categories in EWS

$
0
0
The Categories or Keywords properties on a Mailbox Item is one of the more commonly used Item properties in Exchange. When you want to search for Items with a particular Category set it does present some challenges in EWS.

With EWS you have 3 different search methods, the first being Restrictions (or SearchFilter's if your using the Managed API) that work like MAPI restrictions although you can't build restriction that are 100% equivalent to what you can in MAPI. One particular case is with the Categories property, because this is a Multi-Valued property (or String Array) the IsEqual and Contains Restrictions wont work like the Sproperty restriction in MAPI http://msdn.microsoft.com/en-us/library/office/cc815385(v=office.15).aspx

So the next type of Search you can do is a Search of a Mailbox folder using an AQS querystring which essentially does an Index search. Because the Categories property is an Indexed property this will work fine for Categories. The thrid type of Search you can do is eDiscovery in Exchange 2013 which I'll cover in another post

The following script does a search of the the Inbox folder for a particular Keyword using the AQS query

"System.Category:Categorytolookfor"

It also does a client side validation to ensure no false positives are included. To run the script just pass in the name of the mailbox you want to search and the Category to search for (enclosed in '' if there is a space) eg .\SearchCategory.ps1 glen@domain.com 'green category' . The script will output a CSV report of all the messages founds with that particular Category set.

I've put a download of this script here the code itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4. $CategoryToFind = $args[1]  
  5.   
  6. ## Load Managed API dll    
  7.   
  8. ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT  
  9. $EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")  
  10. if (Test-Path $EWSDLL)  
  11.     {  
  12.     Import-Module $EWSDLL  
  13.     }  
  14. else  
  15.     {  
  16.     "$(get-date -format yyyyMMddHHmmss):"  
  17.     "This script requires the EWS Managed API 1.2 or later."  
  18.     "Please download and install the current version of the EWS Managed API from"  
  19.     "http://go.microsoft.com/fwlink/?LinkId=255472"  
  20.     ""  
  21.     "Exiting Script."  
  22.     exit  
  23.     }  
  24.     
  25. ## Set Exchange Version    
  26. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  27.     
  28. ## Create Exchange Service Object    
  29. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  30.     
  31. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  32.     
  33. #Credentials Option 1 using UPN for the windows Account    
  34. $psCred = Get-Credential    
  35. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  36. $service.Credentials = $creds        
  37.     
  38. #Credentials Option 2    
  39. #service.UseDefaultCredentials = $true    
  40.     
  41. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  42.     
  43. ## Code From http://poshcode.org/624  
  44. ## Create a compilation environment  
  45. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  46. $Compiler=$Provider.CreateCompiler()  
  47. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  48. $Params.GenerateExecutable=$False  
  49. $Params.GenerateInMemory=$True  
  50. $Params.IncludeDebugInformation=$False  
  51. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  52.   
  53. $TASource=@' 
  54.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  55.     public class TrustAll : System.Net.ICertificatePolicy { 
  56.       public TrustAll() {  
  57.       } 
  58.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  59.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  60.         System.Net.WebRequest req, int problem) { 
  61.         return true; 
  62.       } 
  63.     } 
  64.   } 
  65. '@   
  66. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  67. $TAAssembly=$TAResults.CompiledAssembly  
  68.   
  69. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  70. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  71. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  72.   
  73. ## end code from http://poshcode.org/624  
  74.     
  75. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  76.     
  77. #CAS URL Option 1 Autodiscover    
  78. $service.AutodiscoverUrl($MailboxName,{$true})    
  79. "Using CAS Server : " + $Service.url     
  80.      
  81. #CAS URL Option 2 Hardcoded    
  82.     
  83. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  84. #$service.Url = $uri      
  85.     
  86. ## Optional section for Exchange Impersonation    
  87.     
  88. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  89.   
  90. $AQSString = "System.Category:`"" + $CategoryToFind + "`""  
  91. # Bind to the Inbox Folder  
  92. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  93. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  94. $rptCollection = @()  
  95. #Define ItemView to retrive just 1000 Items      
  96. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)      
  97. $fiItems = $null      
  98. do{      
  99.     $fiItems = $service.FindItems($Inbox.Id,$AQSString,$ivItemView)      
  100.     #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  101.     foreach($Item in $fiItems.Items){  
  102.         #Validate exact Category Match  
  103.         $match = $false  
  104.         foreach($cat in $Item.Categories){  
  105.             if($cat.ToLower() -eq $CategoryToFind.ToLower()){  
  106.                 $match = $true;  
  107.             }  
  108.         }  
  109.         if($match){  
  110.             $rptObj = "" | Select DateTimeReceived,From,Subject,Size,Categories    
  111.             $rptObj.DateTimeReceived = $Item.DateTimeReceived    
  112.             $rptObj.From  = $Item.From.Name    
  113.             $rptObj.Subject = $Item.Subject    
  114.             $rptObj.Size = $Item.Size  
  115.             $rptObj.Categories = [system.String]::Join(",",$Item.Categories)  
  116.             $rptCollection += $rptObj  
  117.         }  
  118.     }      
  119.     $ivItemView.Offset += $fiItems.Items.Count      
  120. }while($fiItems.MoreAvailable -eq $true)   
  121. $rptCollection | Export-Csv -NoTypeInformation -Path c:\temp\$MailboxName-CategoryReport.csv  
  122. Write-Host "Report Saved to c:\temp\$MailboxName-CategoryReport.csv"   


Viewing all articles
Browse latest Browse all 241

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>