Monday, June 18, 2012

EWS Managed API and Powershell How-To Series Part 10 Message Classifications

In this part of the how-to series I'm going to look at message classifications and how you can make use of these in your EWS scripts. Message classification was introduced in Exchange 2007 to comply with Organization policies and regulations.

Technical stuff

The extended MAPI properties and X-headers that are used for classification are documented in the following protocol document http://msdn.microsoft.com/en-us/library/ee217686%28v=EXCHG.80%29.aspx .  

Lets go over then quickly


PidLidClassificationGuid is the extended property that contains the GUID of the classification that has been applied to a message. To work out these GUID's you need to use the Exchange Management Shell Get-MessageClassification cmdlet eg


So the ClassificationID = PidLidClassificationGuid

PidLidClassified : Is a Boolean property that tells if a message has been classified

PidLidClassificationDescription: The property either represents the Recipient Description on a message that is received or the Sender Description on a message that is sent.

PidLidClassification: = The displyName of the classification

Sending a Classified Message

To send a classified message with EWS you need to set these Extended Mapi properties the two Mandatory properties you need to set are the  PidLidClassified and PidLidClassificationGuid Exchange should handle the other properties for you. An example of sending a classified message would look like

  1. $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)  
  2. $message.Subject = "Test"  
  3. $message.Body = "Test 123"  
  4. $message.ToRecipients.Add("user@domain.com")  
  5. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  6. $message.SetExtendedProperty($PidLidClassificationGuid"e67e794b-f6d1-4c8f-9f63-1118d21dafa6");  
  7. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,34229,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Boolean);  
  8. $message.SetExtendedProperty($PidLidClassified$true);  
  9. $message.Send.Invoke()  

Finding Classified Messages

To search for classified messages within a mailbox you need to create a searchfilter based around the parameters you want to search on eg. if you have multiple classifications and you just want to limit your search to all classified messages (not just one type of classification) then you can use an exists Search filter to search for only those messages where the classification properties have been set for example

  1. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  2. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  3.   
  4. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  5. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  6. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x85B6,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  7.   
  8. $psPropertySet.Add($PidLidClassificationGuid)  
  9. $psPropertySet.Add($PidLidClassified)  
  10.   
  11. $ItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists($PidLidClassificationGuid)  
  12. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  13. $ivItemView.PropertySet = $psPropertySet  
  14.   
  15. do{    
  16.     $fiResults = $Inbox.findItems($ItemSearchFilter,$ivItemView)    
  17.     foreach($Item in $fiResults.Items){  
  18.         $classificationGUID = $null  
  19.         [Void]$Item.TryGetProperty($PidLidClassificationGuid,[ref]$classificationGUID)  
  20.         $Classification = $null  
  21.         [Void]$Item.TryGetProperty($PidLidClassified,[ref]$Classification)  
  22.         "Subject : " + $Item.Subject  
  23.         "Received : " + $Item.DateTimeReceived  
  24.         "Classification : " + $Classification  
  25.         "ClassificationGUID : " + $classificationGUID  
  26.     }             
  27.     $ivItemView.Offset += $fiResults.Items.Count    
  28. }while($fiResults.MoreAvailable -eq $true)  

If you want to search all folders in a mailbox for message with a particular classification you can either create a searchfilter based on the ClassificationGUID eg
  1. $sfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo($PidLidClassificationGuid"e67e794b-f6d1-4c8f-9f63-1118d21dafa6")  
Or use the above code and do some client side filtering. Depending on the size of the result sets involved you may find doing client side filtering gives better performance the doing a string match on an un-indexed property. Here is a sample for searching all folders in a mailbox for messages with a particular Message classification GUID and doing client side filter on that match and then producing a CSV report of the location of these messages.

  1. $RptObjColl = @()  
  2. $MailboxName = "user@domain.com"  
  3.   
  4. $guid = "e67e794b-f6d1-4c8f-9f63-1118d21dafa6"  
  5.   
  6. ## Load Managed API dll    
  7. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  8.     
  9. ## Set Exchange Version    
  10. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  11.     
  12. ## Create Exchange Service Object    
  13. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  14.     
  15. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  16.     
  17. #Credentials Option 1 using UPN for the windows Account    
  18. $creds = New-Object System.Net.NetworkCredential("glen@domain.com","passwd")     
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}    
  27.     
  28. ## 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    
  29.     
  30. #CAS URL Option 1 Autodiscover    
  31. $service.AutodiscoverUrl($MailboxName,{$true})    
  32. "Using CAS Server : " + $Service.url     
  33.      
  34. #CAS URL Option 2 Hardcoded    
  35.     
  36. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  37. #$service.Url = $uri      
  38.     
  39. ## Optional section for Exchange Impersonation    
  40.     
  41. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  42.   
  43. #Define Function to convert String to FolderPath      
  44. function ConvertToString($ipInputString){      
  45.     $Val1Text = ""      
  46.     for ($clInt=0;$clInt -lt $ipInputString.length;$clInt++){      
  47.             $Val1Text = $Val1Text + [Convert]::ToString([Convert]::ToChar([Convert]::ToInt32($ipInputString.Substring($clInt,2),16)))      
  48.             $clInt++      
  49.     }      
  50.     return $Val1Text      
  51. }     
  52.   
  53. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot,$MailboxName)     
  54. $MsgRoot = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  55.   
  56. $fvFolderView =  New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)    
  57. #Deep Transval will ensure all folders in the search path are returned   
  58.    
  59. $fvFolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;    
  60. $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  61.   
  62.   
  63. $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  64. $PidLidClassificationGuid = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common, 34232,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  65. $PidLidClassified = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,34229,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Boolean);  
  66.   
  67. $psPropertySet.Add($PidLidClassificationGuid)  
  68. $psPropertySet.Add($PidLidClassified)  
  69.   
  70. $FPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  71.   
  72. $PR_Folder_Path = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  73. $FPropertySet.add($PR_Folder_Path)  
  74.   
  75. $fvFolderView.PropertySet = $FPropertySet  
  76. $fiResult = $null    
  77. #The Do loop will handle any paging that is required if there are more the 1000 folders in a mailbox   
  78. $rptHash = @{}  
  79. $ItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+Exists($PidLidClassificationGuid)  
  80. do {   
  81.     $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  82.     $ivItemView.PropertySet = $psPropertySet  
  83.     $fiResult = $Service.FindFolders($folderid,$sfSearchFilter,$fvFolderView)    
  84.     foreach($ffFolder in $fiResult.Folders){    
  85.     "Processing Folder : " + $ffFolder.displayName  
  86.         $foldpathval = $null      
  87.         #Try to get the FolderPath Value and then covert it to a usable String       
  88.         if ($ffFolder.TryGetProperty($PR_Folder_Path,[ref] $foldpathval))      
  89.         {      
  90.             $binarry = [Text.Encoding]::UTF8.GetBytes($foldpathval)      
  91.             $hexArr = $binarry | ForEach-Object { $_.ToString("X2") }      
  92.             $hexString = $hexArr -join ''      
  93.             $hexString = $hexString.Replace("FEFF""5C00")      
  94.             $fpath = ConvertToString($hexString)      
  95.         }      
  96.         if($ffFolder.TotalCount -gt 0){  
  97.             $fiResults = $null  
  98.             $updateColl = @()  
  99.             do{    
  100.                 $fiResults = $ffFolder.findItems($ItemSearchFilter,$ivItemView)  
  101.                 $rptobj = "" | select FolderPath,DateTimeRecieved,Subject,Size,MessageGUID   
  102.                 foreach($Item in $fiResults.Items){    
  103.                     $messageGuid = $null  
  104.                     if($Item.TryGetProperty($PidLidClassificationGuid,[ref]$messageGuid)){  
  105.                         if($messageGuid -eq $guid){  
  106.                             $rptobj.MessageGUID = $messageGuid  
  107.                             $rptobj.FolderPath = $fpath  
  108.                             $rptobj.DateTimeRecieved = $Item.DateTimeReceived  
  109.                             $rptobj.Subject = $Item.Subject  
  110.                             $rptobj.Size = $Item.Size   
  111.                             $RptObjColl += $rptobj  
  112.                         }  
  113.                     }  
  114.                 }    
  115.                 $ivItemView.Offset += $fiResults.Items.Count    
  116.             }while($fiResults.MoreAvailable -eq $true)  
  117.         }           
  118.     }   
  119.     $fvFolderView.Offset += $fiResult.Folders.Count  
  120. }while($fiResult.MoreAvailable -eq $true)   
  121.   
  122. $RptObjColl | Export-Csv -NoTypeInformation c:\Temp\classificationReport.csv  

Thursday, June 07, 2012

How To Series Sample 7 : Reverse Delegate Permissions and Rights Report

The script expands on part 5 of the how to series and produces a reverse permission report of the delegates of all Mailboxes on a server or within a Exchange Org or Exchange Online tenant. This is to help show for a particular delegate what mailboxes that they have been given delegate rights to and if they can see private Items and do they receive Meeting forwards. This script is designed to be run from within a Remote Powershell session that is already connected to your Exchange 2010 org (or from a Exchange Online/Office365 remote Powershell session).


 It uses Get-Mailbox to get all the mailboxes in your org and then it uses the EWS Managed API to connect to each mailbox and query the delegates. It then produces a CSV file that looks like



If you want to understand how it works have a read of the How To Series posts and hopefully you should be able to work out how to customize it if you need to for your own environment. The Script as posted uses EWS Impersonation

If you want to customize which mailboxes it reports on then just change the Get-Mailbox line

Get-Mailbox -ResultSize Unlimited | ForEach-Object{  

eg if you want to limit to only checking one server you could use

Get-Mailbox -ResultSize Unlimited -Server servernameblah | ForEach-Object{

You could do similar with other filter properties such as Database or OU

I've posted a downloadable copy of the script here the script itself look like

  1. ## EWS Managed API Connect Module Script written by Glen Scales  
  2. ## Requires the EWS Managed API and Powershell V2.0 or greator  
  3. $rptArray = New-Object System.Collections.ArrayList  
  4. ## Load Managed API dll  
  5. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"  
  6.   
  7. ## Set Exchange Version  
  8. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1  
  9.   
  10. ## Create Exchange Service Object  
  11. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
  12.   
  13. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
  14.   
  15. #Credentials Option 1 using UPN for the windows Account  
  16. $psCred = Get-Credential  
  17. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
  18. $service.Credentials = $creds      
  19.   
  20. #Credentials Option 2  
  21. #service.UseDefaultCredentials = $true  
  22.   
  23. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
  24.   
  25. [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}  
  26.   
  27.   
  28.   
  29. function CovertBitValue($String){  
  30.     $numItempattern = '(?=\().*(?=bytes)'  
  31.     $matchedItemsNumber = [regex]::matches($String$numItempattern)   
  32.     $Mb = [INT64]$matchedItemsNumber[0].Value.Replace("(","").Replace(",","")  
  33.     return [math]::round($Mb/1048576,0)  
  34. }  
  35.   
  36.   
  37. Get-Mailbox -ResultSize Unlimited | ForEach-Object{   
  38.     $MailboxName = $_.PrimarySMTPAddress.ToString()  
  39.     "Processing Mailbox : " + $MailboxName  
  40.     if($service.url -eq $null){  
  41.         ## 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  
  42.   
  43.         #CAS URL Option 1 Autodiscover  
  44.         $service.AutodiscoverUrl($MailboxName,{$true})  
  45.         "Using CAS Server : " + $Service.url   
  46.           
  47.         #CAS URL Option 2 Hardcoded  
  48.         #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
  49.         #$service.Url = $uri    
  50.     }  
  51.   
  52.     $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)  
  53.     $delegates = $service.getdelegates($MailboxName,$true)    
  54.     foreach($Delegate in $delegates.DelegateUserResponses){    
  55.         $rptObj = "" | select Delegate,Mailbox,Inbox,Calendar,Contacts,Tasks,Notes,Journal,MeetingMessages,ViewPrivateItems    
  56.         $rptObj.Mailbox = $MailboxName  
  57.         $rptObj.Delegate = $Delegate.DelegateUser.UserId.PrimarySmtpAddress    
  58.         $rptObj.Inbox = $Delegate.DelegateUser.Permissions.InboxFolderPermissionLevel    
  59.         $rptObj.Calendar = $Delegate.DelegateUser.Permissions.CalendarFolderPermissionLevel    
  60.         $rptObj.Contacts = $Delegate.DelegateUser.Permissions.ContactsFolderPermissionLevel    
  61.         $rptObj.Tasks = $Delegate.DelegateUser.Permissions.TasksFolderPermissionLevel    
  62.         $rptObj.Notes = $Delegate.DelegateUser.Permissions.NotesFolderPermissionLevel    
  63.         $rptObj.Journal = $Delegate.DelegateUser.Permissions.JournalFolderPermissionLevel    
  64.         $rptObj.ViewPrivateItems = $Delegate.DelegateUser.ViewPrivateItems    
  65.         $rptObj.MeetingMessages = $Delegate.DelegateUser.ReceiveCopiesOfMeetingMessages   
  66.         [Void]$rptArray.Add($rptObj)  
  67.             
  68.     }    
  69. }  
  70. $rptArray | Sort-Object Delegate | Export-Csv -Path c:\temp\ReverseDelegateReport.csv -NoTypeInformation