Monday, December 14, 2015

Showing the Calendar Configuration of a Mailbox or Meeting Room using EWS

When you configure Calendar processing settings in Exchange either using the Exchange Administrator Centre via the Exchange Management Shell (Set-CalendarProcessing) many of these setting get held in a FAI (Folder Associated Item) in the Calendar Folder of the Mailbox in question. In EWS you can access these configuration objects using the UserConfiguration operation and classes.

The Calendar settings are stored in the Roaming Dictionary format to store each of the different Key and Value pairs. For some of the settings like the bookin policy (In-policy meeting requests) and (Out-of-policy meeting requests) these are stored as an array of ExchangeDn's.

I've put together a script cmdlet called Show-CalendarSettings that can dump out the Roaming dictionary setting for a Calendar Configuration object using EWS. And also for the BookIn and RequestIn policy it will loop through each of the ExchangeDn's in the array and try to resolve each of the entries via ResolveName . All the configuration information is written to file and the results of the ResolveName is written along with the result (eg valid if it resolves couldn't resolve if not). eg it produces an output like




  I've put the script on GitHub here https://github.com/gscales/Powershell-Scripts/blob/master/DumpCalSettings.ps1 and the script itself look like

function Show-CalendarSettings
{
    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
    )  
  Begin
 {
  $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)
  }
  # Bind to the Calendar Folder
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
  $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "Calendar", $Calendar.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
  #$UsrConfig.Dictionary
  $rptCollection = @()
  foreach($cnfObj in $UsrConfig.Dictionary.Key){
   $rptObj = "" | Select Property,Value,Valid
   $rptObj.Property = $cnfObj
   $rptObj.Valid = "Ok"
   $rptObj.Value = $UsrConfig.Dictionary[$cnfObj]
   $rptCollection +=$rptObj
   if($cnfObj -eq "BookInPolicyLegDN")
   {
    foreach($LegDn in $UsrConfig.Dictionary["BookInPolicyLegDN"])
    {
        $ncCol = $service.ResolveName($LegDn, [Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::DirectoryOnly, $false);
           if($ncCol.Count -gt 0){
      #Write-output ("Found " + $ncCol[0].Mailbox.Address)
      $rptObj = "" | Select Property,Value,Valid
      $rptObj.Property = "BookInPolicyValue"
      $rptObj.Value = $ncCol[0].Mailbox.Address
      $rptObj.Valid = "Ok"
      $rptCollection +=$rptObj
           }
     else
     { 
      #Write-Output "Couldn't resolve " + $LegDn
      $rptObj = "" | Select Property,Value,Valid
      $rptObj.Property = "BookInPolicyValue"
      $rptObj.Value = $LegDn
      $rptObj.Valid = "Couldn't resolve"
      $rptCollection +=$rptObj
     }
     
    } 
   }
   if($cnfObj -eq "RequestInPolicyLegDN")
   {
    foreach($LegDn in $UsrConfig.Dictionary["RequestInPolicyLegDN"])
    {
        $ncCol = $service.ResolveName($LegDn, [Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::DirectoryOnly, $false);
           if($ncCol.Count -gt 0){
      #Write-output ("Found " + $ncCol[0].Mailbox.Address)
      $rptObj = "" | Select Property,Value,Valid
      $rptObj.Property = "RequestInPolicyValue"
      $rptObj.Value = $ncCol[0].Mailbox.Address
      $rptObj.Valid = "Ok"
      $rptCollection +=$rptObj
           }
     else
     { 
      #Write-Output "Couldn't resolve " + $LegDn
      $rptObj = "" | Select Property,Value,Valid
      $rptObj.Property = "RequestInPolicyValue"
      $rptObj.Value = $LegDn
      $rptObj.Valid = "Couldn't resolve"
      $rptCollection +=$rptObj
     }
     
    }   
   }
  }
  Write-Output $rptCollection
   
  $rptCollection | Export-Csv -Path ("$MailboxName-CalendarSetting.csv") -NoTypeInformation
 }
}

Wednesday, December 02, 2015

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)  
 }
}


Tuesday, November 17, 2015

Finding the TimeZone being used in a Mailbox using EWS

If you ever have the need to create a number of events in user mailbox's from a central application or Script where the target Mailboxes span across different time zones then finding each target Mailbox's timezone is a critical thing. In this post I'm going to outline a few different methods of getting the TimeZone using EWS.

If you have access to the Exchange Management Shell cmdlet's to find the users configured timezone you can use either the Get-MailboxCalendarConfiguration or Get-MailboxRegionalConfiguration cmdlets which show you the timezone settings of a Mailbox from the WorkHours configuration of that mailbox. The object in the Mailbox that the information is read from/stored in is the IPM.Configuration.WorkHours FAI (Folder Assoicated Items) object in the Calendar Folder of the Mailbox. So if you want to access the TimeZone setting in Mailbox just using EWS you need to Bind to this UserConfiguration object (FAI object) and then parse the TimeZone Settings out of the WorkHours configuration XML document(which is documented in https://msdn.microsoft.com/en-us/library/ee157798(v=exchg.80).aspx) eg in Powershell something like the following should work okay

function GetWorkHoursTimeZone
{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the Calendar Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
   $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.WorkHours") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($Calendar.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "WorkHours", $Calendar.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    [XML]$WorkHoursXMLString = [System.Text.Encoding]::UTF8.GetString($UsrConfig.XmlData) 
    $returnVal = $WorkHoursXMLString.Root.WorkHoursVersion1.TimeZone.Name
    write-host ("Parsed TimeZone : " + $returnVal)
    Write-Output $returnVal
   }
   else
   {
    write-host ("No Workhours Object in Mailbox")
    Write-Output $null
   }
 }
}

 The other place in an Exchange Malbox where TimeZone information is held is in the OWA Configuration. This is set when a user logs onto to OWA the first time and then selects the timezone, the configuration is then stored in another FAI (in a Roaming Dictionary)with an ItemClass of IPM.Configuration.OWA.UserOptions in the NON_IPM root of the mailbox. Eg the following can be used to access this setting using EWS

function GetOWATimeZone{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the RootFolder Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
   $RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.OWA.UserOptions") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($RootFolder.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "OWA.UserOptions", $RootFolder.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    if($UsrConfig.Dictionary.ContainsKey("timezone"))
    {
     $returnVal = $UsrConfig.Dictionary["timezone"]
     write-host ("OWA TimeZone : " + $returnVal)
     Write-Output $returnVal
    }
    else
    {
     write-host ("TimeZone not set")
     Write-Output $null
    }
    
    
   }
   else
   {
    write-host ("No Workhours OWAConfig for Mailbox")
    Write-Output $null
   }
 }
}

If you tried both of these locations and still can't find the TimeZone (or your get a conflicting result) the last method you could try is to enumerate the last X number of appointments that where created by the user in the calendar (either a meeting they organized or a non meeting) and then enumerate the timezone used on those objects. The following is a sample of using the Calendar Appointments to work out the timezone of the user (It should return the most commonly used timezone base on the last 150 Calendar items).

function GetTimeZoneFromCalendarEvents{
    param( 
  [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
  $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $tzList = [TimeZoneInfo]::GetSystemTimeZones()
  $AppointmentStateFlags = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8217,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ResponseStatus = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8218,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(150)  
  $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
  $psPropset.Add($AppointmentStateFlags)
  $psPropset.Add($ResponseStatus)
  $ivItemView.PropertySet = $psPropset
  $fiItems = $service.FindItems($Calendar.Id,$ivItemView)
  $tzCount = @{}
  if($fiItems.Items.Count -gt 0){
   foreach($Item in $fiItems.Items){
    $AppointmentStateFlagsVal = $null
    [Void]$Item.TryGetProperty($AppointmentStateFlags,[ref]$AppointmentStateFlagsVal)
    $ResponseStatusVal = $null
    [Void]$Item.TryGetProperty($ResponseStatus,[ref]$ResponseStatusVal)
    if($ResponseStatusVal -eq "Organizer" -bor $AppointmentStateFlagsVal -eq 0)
    {
     if($tzCount.ContainsKey($Item.TimeZone))
     {
      $tzCount[$Item.TimeZone]++
     }
     else
     {
      $tzCount.Add($Item.TimeZone,1)
     }
    }
   }    
  }
  $returnVal = $null
  if($tzCount.Count -gt 0){
   $fav = ""
   $tzCount.GetEnumerator() | sort -Property Value -Descending | foreach-object {
      if($fav -eq "")
      {
         $fav = $_.Key
      }
   }
    foreach($tz in $tzList)
   {
    if($tz.DisplayName -eq $fav)
    {
     $returnVal = $tz.Id
    }
   }
  }
  Write-Host ("TimeZone From Calendar Appointments : " + $returnVal)
  Write-Output $returnVal
 }
}

I've included all of these functions in a module that I've posted on GitHub here

Tuesday, October 27, 2015

Using eDiscovery to do a Multi Mailbox search for Mailbox Item Statistics in Exchange

eDiscovery in Exchange 2013 and above has a multitude of uses when it comes to both data discovery and also reporting. One thing you can do with eDiscovery is run a single Query across multiple mailboxes using one request. A couple of month ago I posted this eDiscovery Powershell module on GitHub . This module has a number of cmdlets that does single mailbox queries using eDiscovery so I've created a new cmdlet Search-MultiMailboxesItemStats  for doing Multi Mailbox queries. This allows you to pass in an array of mailboxes you want processed and it will return statistics about how many Items and the Size of those items in bytes based on that query. For example to Query the number of Email received in the last month across a number of mailboxes use

Search-MultiMailboxesItemStats -Mailboxes @('mailbox@domain.com','mailbox2@domain.com')  -QueryString ('Received>' + (Get-Date).AddDays(-31).ToString("yyyy-MM-dd"))

And it will output something like

 
Or if you just want to look at the email that came from a specific domain you could use

Search-MultiMailboxesItemStats -Mailboxes @('mailbox@domain.com','mailbox2@domain.com')  -QueryString ('Received>' + (Get-Date).AddDays(-31).ToString("yyyy-MM-dd") + " AND From:yahoo.com")

another example eg search for the number of contacts in each Mailbox

Search-MultiMailboxesItemStats -Mailboxes @('mailbox@domain.com','mailbox2@domain.com')  -QueryString 'kind:contacts'


The latest version of the module is posted up on GitHub here or you can download a copy from here

Tuesday, October 20, 2015

Introducing the Data Rumble Message Tracking Outlook AddIn for Office 365

With great pride and a little trepidation I'd like to introduce my new venture Data Rumble and our first software release Message Tracking Outllook Addin for Office 365. As a company we are looking to focus on email data so looking at the Metadata an Email message picks up and leaves behind while its in transit to and from a mailbox is the logical first step for us. Launching something new is a lot of work so this first release is a bit of dry run to get all the underlying infrastructure and procedures in place.

At release the main feature of this AddIn is that it allows you to perform a Message Trace on a Message from within Outlook itself using the Office365 Reporting Web Service. This is a REST endpoint that allows you to perform a number of different Office365 Administrative reporting tasks it has been around for a couple of years now and pre dates some of the oauth features that the newer mailbox REST services have so I expect the Endpoint will change soon  (it also has the option to use PowerShell as an alternative to cater for instances where REST doesn't work). . But from this AddIn's perspective it makes use of this endpoint to perform a Message Trace (that you would normally do in the EAC or PowerShell eg https://technet.microsoft.com/EN-US/library/jj200741(v=exchg.150).aspx ) from within Outlook eg. this a screenshot


The Addin post processes the data returned by the Reporting service as well as data extracted from the messages Transport Headers and a few other Message properties and combines those together to provide more information around the message such as the Message header properties, Exchange online protection actions etc (although there is already a good tool for this https://testconnectivity.microsoft.com/ and a corresponding AddIn but this is just another view of the data),Sender and Recipient information. All Message Tracking is done based on the MessageId's extracted from the message in Outlook, it also extracts any associated MessageID's eg if this message is a reply, forward or part of a thread. So you can then query the logs for any associated Messages as well as query for other messages that have been sent or received to and from any of the sender, recipients or envelope recipients found in the log. (envelope recipients would could be BCC's, alternate recipients, forwards or recipients added by a Transport Agent that are available in the Tracing logs). I've created a short video below to showcase the features or you can check and download the software from the product page here.

Tuesday, October 06, 2015

Unread email ews Powershell Module with reply and forward counting

I've done a few of these Unread / Unused mailbox scripts over the years but this one has a bit of a difference. As well as counting the Total number of unread email in the Inbox over a certain period of time it uses the PidTagLastVerbExecuted property to count how many email messages over that period of time had the client action ReplytoSender, ReplyAll or forwarded and also the number of email in the SentItems folder. This property is set on messages in the Inbox message when one of those actions is taken by the client so it is useful for tracking the use of Mailboxes and gathering statistics around how they are being used. eg here are a few samples of running this module



The code uses both EWS and the Exchange Management Shell to get information about the Mailbox so you need to run it from within the EMS or a Remote PowerShell session (see this if your running it from Office365). I've put the script up on GitHub or you can download it from here. I've also created a Search Filter version of the code, this would work on Exchange 2007 and also if you have an issue where you only see a maximum of 250 items (which is an AQS bug in some version of Exchange) this will address this issue this is also on gihub here


The code itself looks like

function Connect-Exchange{ 
    param( 
     [Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [System.Management.Automation.PSCredential]$Credentials,
  [Parameter(Position=2, Mandatory=$false)] [string]$url
    )  
  Begin
   {
  Load-EWSManagedAPI
  
  ## Set Exchange Version  
  $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1
    
  ## Create Exchange Service Object  
  $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
    
  ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
    
  #Credentials Option 1 using UPN for the windows Account  
  #$psCred = Get-Credential  
  $creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
  $service.Credentials = $creds      
  #Credentials Option 2  
  #service.UseDefaultCredentials = $true  
   #$service.TraceEnabled = $true
  ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
    
  Handle-SSL 
    
  ## 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  
    
  #CAS URL Option 1 Autodiscover  
  if($url){
   $uri=[system.URI] $url
   $service.Url = $uri    
  }
  else{
   $service.AutodiscoverUrl($MailboxName,{$true})  
  }
  Write-host ("Using CAS Server : " + $Service.url)   
     
  #CAS URL Option 2 Hardcoded  
    
  #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
  #$service.Url = $uri    
    
  ## Optional section for Exchange Impersonation  
    
  #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
  if(!$service.URL){
   throw "Error connecting to EWS"
  }
  else
  {  
   return $service
  }
 }
}

function Load-EWSManagedAPI{
    param( 
    )  
  Begin
 {
  ## Load Managed API dll  
  ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
  $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")
  if (Test-Path $EWSDLL)
      {
      Import-Module $EWSDLL
      }
  else
      {
      "$(get-date -format yyyyMMddHHmmss):"
      "This script requires the EWS Managed API 1.2 or later."
      "Please download and install the current version of the EWS Managed API from"
      "http://go.microsoft.com/fwlink/?LinkId=255472"
      ""
      "Exiting Script."
      exit
      } 
   }
}

function Handle-SSL{
    param( 
    )  
  Begin
 {
  ## Code From http://poshcode.org/624
  ## Create a compilation environment
  $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
  $Compiler=$Provider.CreateCompiler()
  $Params=New-Object System.CodeDom.Compiler.CompilerParameters
  $Params.GenerateExecutable=$False
  $Params.GenerateInMemory=$True
  $Params.IncludeDebugInformation=$False
  $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
  $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
  $TAAssembly=$TAResults.CompiledAssembly

  ## We now create an instance of the TrustAll and attach it to the ServicePointManager
  $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
  [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

  ## end code from http://poshcode.org/624

 }
}

function CovertBitValue($String){  
    $numItempattern = '(?=\().*(?=bytes)'  
    $matchedItemsNumber = [regex]::matches($String, $numItempattern)   
    $Mb = [INT64]$matchedItemsNumber[0].Value.Replace("(","").Replace(",","")  
    return [math]::round($Mb/1048576,0)  
}  

function Get-UnReadMessageCount{
    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]$Months
    )  
  Begin
 {
  $eval1 = "Last" + $Months + "MonthsTotal"
  $eval2 = "Last" + $Months + "MonthsUnread"
  $eval3 = "Last" + $Months + "MonthsSent"
  $eval4 = "Last" + $Months + "MonthsReplyToSender"
  $eval5 = "Last" + $Months + "MonthsReplyToAll"
  $eval6 = "Last" + $Months + "MonthForward"
  $reply = 0;
  $replyall = 0
  $forward = 0
  $rptObj = "" | select  MailboxName,Mailboxsize,LastLogon,LastLogonAccount,$eval1,$eval2,$eval4,$eval5,$eval6,LastMailRecieved,$eval3,LastMailSent  
  $rptObj.MailboxName = $MailboxName  
  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) 
  }
  $AQSString1 = "System.Message.DateReceived:>" + [system.DateTime]::Now.AddMonths(-$Months).ToString("yyyy-MM-dd")   
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)     
  $SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)    
  $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)  
  $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)  
  $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)
  $psPropset.Add([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead)
  $PidTagLastVerbExecuted = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x1081,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer); 
  $psPropset.Add($PidTagLastVerbExecuted)
  $ivItemView.PropertySet = $psPropset
    $MailboxStats = Get-MailboxStatistics $MailboxName  
  $ts = CovertBitValue($MailboxStats.TotalItemSize.ToString())  
  write-host ("Total Size : " + $MailboxStats.TotalItemSize) 
     $rptObj.MailboxSize = $ts  
  write-host ("Last Logon Time : " + $MailboxStats.LastLogonTime) 
  $rptObj.LastLogon = $MailboxStats.LastLogonTime  
  write-host ("Last Logon Account : " + $MailboxStats.LastLoggedOnUserAccount ) 
  $rptObj.LastLogonAccount = $MailboxStats.LastLoggedOnUserAccount  
  $fiItems = $null
  $unreadCount = 0
  $settc = $true
     do{ 
   $fiItems = $Inbox.findItems($AQSString1,$ivItemView)  
   if($settc){
    $rptObj.$eval1 = $fiItems.TotalCount  
    write-host ("Last " + $Months + " Months : " + $fiItems.TotalCount)
    if($fiItems.TotalCount -gt 0){  
        write-host ("Last Mail Recieved : " + $fiItems.Items[0].DateTimeReceived ) 
        $rptObj.LastMailRecieved = $fiItems.Items[0].DateTimeReceived  
    }      
    $settc = $false
   }
       foreach($Item in $fiItems.Items){
     $unReadVal = $null
     if($Item.TryGetProperty([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::IsRead,[ref]$unReadVal)){
      if(!$unReadVal){
       $unreadCount++
      }
     } 
       $lastVerb = $null
     if($Item.TryGetProperty($PidTagLastVerbExecuted,[ref]$lastVerb)){
      switch($lastVerb){
       102 { $reply++ }
       103 { $replyall++}
       104 { $forward++}
      }
     } 
       }    
       $ivItemView.Offset += $fiItems.Items.Count    
   }while($fiItems.MoreAvailable -eq $true) 

  write-host ("Last " + $Months + " Months Unread : " + $unreadCount ) 
  $rptObj.$eval2 = $unreadCount  
  $rptObj.$eval4 = $reply
  $rptObj.$eval5 = $replyall
  $rptObj.$eval6 = $forward
  $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)  
  $fiResults = $SentItems.findItems($AQSString1,$ivItemView)  
  write-host ("Last " + $Months + " Months Sent : " + $fiResults.TotalCount  )
  $rptObj.$eval3 = $fiResults.TotalCount  
  if($fiResults.TotalCount -gt 0){  
      write-host ("Last Mail Sent Date : " + $fiResults.Items[0].DateTimeSent  )
      $rptObj.LastMailSent = $fiResults.Items[0].DateTimeSent  
  }  
  Write-Output $rptObj  
 }
}