Cancel future meetings in a mailbox

One of the long-running woes of the Exchange admin is that you can’t transfer “ownership” of a meeting to someone else when the owner leaves the company. While you still can’t do that, Microsoft recently announced the Remove-CalendarEvents cmdlet for mailboxes in Exchange Online.  Its intention is to allow the administrator to cancel all future meetings for a terminated employee so that someone else can create new meetings in their place.

Because it works only for cloud mailboxes, I wrote a script to do the same thing for on-premises mailboxes (though it will also work for cloud mailboxes).  It uses EWS to get all future meetings for a mailbox and cancel them.  The default settings are to cancel all meetings that occur in the next year where the mailbox is the organizer.  You can also choose to have it cancel (decline) meetings where the mailbox is an attendee, and you can specify text that should be added to the cancellation or decline message.  Additionally, if you don’t want to wholly cancel recurring meetings because the history of all those occurrences will be lost for the attendees, you can instead have organized recurring meetings end so that only future occurrences are canceled, but historical occurrences remain.

Because of the way calendar items are stored, you can get an item and then see when it occurs, if it is recurring, etc., but if it is a recurring meeting you only see the first occurrence.  To work with occurrences, you use a calendar view (time frame) and let Exchange worry about whether an occurrence of a recurring item should be included in the window.  But you can have multiple occurrences of the same meeting in the time frame, and you want to delete the series, not an occurrence.  In a calendar view, you can see if a meeting is an occurrence and, if so, get the corresponding master for that series.

Once the series is canceled (or ended, if you choose that option), there still can be more occurrences of that canceled series in the search results.  If you try and get the recurring master for an occurrence whose master has already been canceled, you’ll get an error.  So, these occurrences can be skipped, but you have to know which ones can be skipped.  To solve that, I store the recurring meeting’s global object ID (which is the same for a recurring master and all of its occurrences because it is really just one meeting as stored in the calendar) in an array.  For every meeting in the search results that is an occurrence, I check if the global object ID is in the array.  If so, I skip it because its master has already been deleted.  If not, I add the global object ID to the array, then cancel the meeting.

The script has comment-based help so you know what all the parameters are for, and there are inline comments so you can see what is being done throughout.  While you can use current credentials or specify one, if you want it to prompt if you don’t specify credentials and don’t want to use default credentials, you can comment and uncomment the the necessary lines at 81-84.  Likewise for the EWS URL, it is hard-coded to EXO, which you can change, but if you want to use autodiscover, you can comment and uncomment the necessary lines at 91-93.

Download the script via the link below, but you can see the code and copy it below, too.

  Cancel-MailboxMeetings.ps1 (8.7 KiB)

<#
	.Synopsis
		Cancel meetings within a specified timeframe for a mailbox
	.Description
		Ideal for terminated employees, this script will cancel all meetings
		organized by the mailbox, and optionally where the mailbox is an attendee,
		within a given timeframe.  The default is one year from run time.
	.Parameter EmailAddress
		Email address of the mailbox to process.  Pipeline support allows piping
		from Get-Mailbox.
	.Parameter StartDate
		Start date of the timeframe to cancel.  Default is now.
	.Parameter EndDate
		End date of the timeframe to cancel.  Default is one year from now.
	.Parameter IncludeAttendeeMeetings
		Switch to also cancel meetings where the mailbox is an attendee
	.Parameter EndOrganizedRecurringMeetings
		Switch to end organized recurring meetings instead of canceling them.
		The end date of the recurrence is set to the cmdlet's StartDate.  This will leave 
		past meeting occurrences on attendee calendars.		
	.Parameter CancellationText
		Text to add to the body of the cancellation message
	.Parameter Credential
		Optional credential object to use instead of asking for or using current credentials
	.Parameter UseImpersonation
		Switch parameter to use impersonation instead of FMA or folder permission
	.Example
		Cancel-MailboxMeetings.ps1 -EmailAdress johndoe@company.com
	.Example
		Cancel-MailboxMeetings.ps1 janedoe@company.com "6/1/17" "8/1/17" -IncludeAttendeeMeetings -CancellationText "Jane is no longer here."
	.Example
		Get-Mailbox johndoe | Cancel-MailboxMeetings.ps1 -Credential (Get-Credential) -EndOrganizedRecurringMeetings
	.Notes
		Required permission: 
			*Editor role to calendar will work for meetings (attendee or organizer)
			- or -
			*Impersonation right to the target mailbox
			- or -
			*Full mailbox access; Send As is not required
		Version: 1.2
		Date: 7/3/17
#>
#Version 3 is only required because of use of the [pscredential] type accelerator for the Credential parameter
#requires -Version 3
[CmdletBinding(SupportsShouldProcess=$false)]
Param (
	[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Email address of user")]
		[Alias("PrimarySMTPAddress")][string]$EmailAddress,
	[Parameter(Position=1,Mandatory=$false)][DateTime]$StartDate = (Get-Date),
	[Parameter(Position=2,Mandatory=$false)][DateTime]$EndDate = (Get-Date).AddDays(365),
	[switch]$IncludeAttendeeMeetings,
	[switch]$EndOrganizedRecurringMeetings,
	[Parameter(Mandatory=$false)][string]$CancellationText,	
	[Parameter(Mandatory=$false)][PSCredential]$Credential,
	[switch]$UseImpersonation
	)

begin
	{
	#Check for EWS API
	$apiPath = (($(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 $apiPath)
		{
		Add-Type -Path $apiPath
		}
	else
		{
		Write-Error "The Exchange Web Services Managed API is required to use this script." -Category NotInstalled
		break
		}

	$exchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2
	$exchangeService = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ExchangeService($exchangeVersion) 
	}

process
	{
	if (-not($Credential))
		{
		#$Credential = Get-Credential
		#$exchangeService.Credentials = New-Object -TypeName Microsoft.Exchange.WebServices.Data.WebCredentials($Credential)
		# Or
		$exchangeService.UseDefaultCredentials = $true
		}
	else
		{
		$exchangeService.Credentials = New-Object -TypeName Microsoft.Exchange.WebServices.Data.WebCredentials($Credential)
		}

	#$exchangeService.AutodiscoverUrl($EmailAddress, {$true})
	#Or use hard-coded URL
	$exchangeService.Url = "https://outlook.office365.com/EWS/Exchange.asmx"

	if ($UseImpersonation)
		{
		$exchangeService.ImpersonatedUserId = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(
			[Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $mailbox.EmailAddress)
		}
	
	#Bind to the calendar
	$folderID = New-Object -TypeName Microsoft.Exchange.WebServices.Data.FolderId(
		[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$EmailAddress)
	$calFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($exchangeService,$folderID)

	#Create a view to get all events during the specified timeframe
	$calendarView = New-Object -TypeName Microsoft.Exchange.WebServices.Data.CalendarView($StartDate, $EndDate)
	$properties = New-Object -TypeName Microsoft.Exchange.WebServices.Data.PropertySet(
		[Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
	#Add Clean Global Object ID to property set so it can be used to correlate occurrences of the same meeting
	$propCleanGOID = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(
		[Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Meeting, 35,
		[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
	$properties.Add($propCleanGOID)
	$calendarView.PropertySet = $properties
	$searchResult = $exchangeService.FindAppointments($calFolder.Id,$calendarView)

	#region Functions
	function Process-Cancellation ($meeting, $attendeeType, $goid)
		{
		if ($meeting.IsRecurring)
			{
			#Skip processing if recurring master has already been canceled
			if ($meetingIds -notcontains $goid)
				{
				#Determine whether occurrence or master
				if ($meeting.AppointmentType -ne [Microsoft.Exchange.WebServices.Data.AppointmentType]::RecurringMaster)
					{
					#Get recurring master
					$master = [Microsoft.Exchange.Webservices.Data.Appointment]::BindToRecurringMaster($exchangeService,$meeting.Id)
					}
				else
					{
					$master = $meeting
					}
				#Add Global ID to array so remaining occurrences in collection can be ignored
				$meetingIds.Add($goid)
				if ($attendeeType -eq "Organizer")
					{
					#If ending instead of canceling, end only if first occurrence is in the past, else cancel
					if ($EndOrganizedRecurringMeetings -and ($StartDate -gt $master.Recurrence.StartDate))
						{
						Update-MeetingEndDate -meeting $master
						}
					else
						{
						Send-MeetingCancel -meeting $master
						}
					}
				else
					{
					Send-MeetingDecline -meeting $master
					}
				}
			}
		else #Non-recurring meeting
			{
			if ($attendeeType -eq "Organizer")
				{
				Send-MeetingCancel -meeting $meeting
				}
			else
				{
				Send-MeetingDecline -meeting $meeting
				}
			}
		}

	function Update-MeetingEndDate ($meeting)
		{
		$meeting.Recurrence.EndDate = $StartDate
		$meeting.Update([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToAllAndSaveCopy)
		Write-Output "Meeting end date updated: $($meeting.Subject)"
		}
	
	function Send-MeetingCancel ($meeting)
		{
		[void]$meeting.CancelMeeting($CancellationText)
		Write-Output "Meeting canceled: $($meeting.Subject)"
		}
		
	function Send-MeetingDecline ($meeting)
		{
		#Decline method does not support custom message, so create decline message
		if ($CancellationText)
			{
			$declineMessage = $meeting.CreateDeclineMessage()
			$declineMessage.Body = $CancellationText
			[void]$declineMessage.Send()
			Write-Output "Meeting declined: $($meeting.Subject)"
			}
		else
			{
			[void]$meeting.Decline($true)
			Write-Output "Meeting declined: $($meeting.Subject)"
			}		
		}
	#endregion
	
	if ($searchResult.TotalCount -gt 0)
		{
		#Exclude non-meetings
		$meetings = $searchResult.Items | Where-Object {$_.IsMeeting}
		if ($meetings)
			{
			Write-Output "Processing $($meetings.Count) meeting instances."
			#Create array to hold list of recurring master IDs
			$meetingIds = New-Object -TypeName System.Collections.Generic.List[System.String]
			foreach ($item in $meetings)
				{
				#Get meeting global ID from extended properties collection
				$cleanGOID = $null
				[void]$item.TryGetProperty($propCleanGOID, [ref]$cleanGOID)
				
				if ($item.MyResponseType -eq [Microsoft.Exchange.WebServices.Data.MeetingResponseType]::Organizer) #Mailbox is organizer
					{
					Process-Cancellation -meeting $item -attendeeType "Organizer" -goid $cleanGOID
					}
				elseif ($IncludeAttendeeMeetings) #Decline meetings where mailbox is attendee
					{
					Process-Cancellation -meeting $item -attendeeType "Attendee" -goid $cleanGOID
					}
				}
			}
		else
			{
			Write-Output "There are no meetings in the specified timeframe."
			}
		}
	else
		{
		Write-Output "There are no meetings in the specified timeframe."
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *

*