Skip to main content

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

Popular posts from this blog

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...

Downloading a shared file from Onedrive for business using Powershell

I thought I'd quickly share this script I came up with to download a file that was shared using One Drive for Business (which is SharePoint under the covers) with Powershell. The following script takes a OneDrive for business URL which would look like https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filename.txt This script is pretty simple it uses the SharePoint CSOM (Client side object Model) which it loads in the first line. It uses the URI object to separate the host and relative URL which the CSOM requires and also the SharePointOnlineCredentials object to handle the Office365 SharePoint online authentication. The following script is a function that take the OneDrive URL, Credentials for Office365 and path you want to download the file to and downloads the file. eg to run the script you would use something like ./spdownload.ps1 ' https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filen...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.
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.