Powershell script to sync select details of calendar entries from one calendar to another

Recently at work I received a request to sync the calendar of one of our employee’s to the iPhone of a person external to the company. After much deliberation between all of our internal IT teams we decided on the following method:

  1. Created an exchange mailbox that can’t send and receive email for the external user
  2. Installed the Good Mobile app on the external user’s device and activate it against our Good for Enterprise system
  3. Used a PowerShell EWS Script (running every 15 minutes) to copy a rolling 2 years’ worth of entries from the source mailbox to the destination mailbox
    1. For company specified security reasons the script only syncs the Subject, Date/Time, and location of all calendar entries.
    2. If an entry is removed from the source calendar it is removed from the destination calendar along with any entries in the destination calendar that are not present in the source calendar.

Originally I tried to copy the entries from the source mailbox to the destination mailbox but I ran into two issues:

  1. The source account needs full mailbox access to the source account, this is because impersonation is used to access the mailboxes. Which means the copy action is being performed as the source account.
  2. Reoccurring appointments, unlike other appointments, cannot be copied and have to be re-created. So instead of trying to figure out a way to copy them and any changes in the reoccurrence pattern I decided to create new entries for all the appointments.

Below is a copy of the script I created for this task, it’s not great but it’s currently getting the job done.

 

<#
.SYNOPSIS
      Sync-EWSCalendarOneWay.ps1 uses Exchange Web Services to do a one way sync of only the Subject, Start Time, End Time, Free Busy information, 
	  and location information of all calendar items in a given range of runtime of the script up to two years from a source Exchange 2010 mailbox 
	  to a destination Exchange 2010 mailbox. All entries in the same time frame on the destination mailbox calendar that are not in the source 
	  calendar will be deleted. 
.DESCRIPTION
      Sync-EWSCalendarOneWay.ps1 will 1st load the EWS Managed API using the path specified, once loaded the script will create date time objects 
	  using the current runtime date (or a specified date) as the start range and provide day range as the ending range (choosing Midnight for 
	  each date). Then 2 separate EWS service objects are created for the source and destination mailbox using Impersonation (via a credential file
	  or specifed login info) or the current runtime account and EWS URL or auto discover. For each service all the calendar entries for the given 
	  range are pulled. If at least one calendar returns entries then the Source Mailbox Calendar search results are compared to the Destination 
	  Mailbox Search results. Any equal entries are ignored. Any Entries found only in the Source mailbox are saved in an list that will be the
	  additions to the destination calendar. Any Entries found only in the Destination mailbox are saved in a list that will be the deletion to the 
	  destination calendar. 
      If Adds to the destination calendar are found, the script creates new Appointment EWS objects with only the following information : Subject, 
	  Location, Start Time, End Time, If It’s an All Day Event, The Free Busy Status, and the reminder set to false. This new object is then saved 
	  to the destination calendar. Note that the entries from the source are not copied from the destination calendar due to the following:
            1.    This requires the source mailbox to have full access to the destination mailbox
            2.    This script was meant to copy only the basic appointment info and to remove attendee info, Appointment body, etc. 
            3.    You cannot copy reoccurring appointments from one calendar to another using EWS, you would have to create a new reoccurring appointment 
			with the same information at the destination calendar. 
      If Deletes to the destination calendar are found then for each entry:
            1.    A search of is made against the destination calendar for the start and stop time of the appointment to delete with all entries in that time 
			frame returned
            2.    All returned entries are searched for one that matches all the properties of the current entry to delete.
            3.    Once a matching entry found is it is deleted and all other results are ignored and the script moves onto the next Appointment to delete
      Once all Adds and Deletes are processed if any errors are found during then an email detailing the action, subject, start, and stop time of the calendar 
	  entry that error’ed out.  
.PARAMETER SourceMailbox
      The SMTP address on of the source mailbox to pull calendar entries from
.PARAMETER DestinationMailbox
      The SMTP address of the destination mailbox to sync calendar entries to
.PARAMETER TimeToSyncInDays
      The number in days that the search range will encompass, up to a maximum of 730. If none is specified then the default will be 730 days
.PARAMETER StartingDate
      The Starting date of the search range, if none is specified then the default will be the runtime of the script 
.PARAMETER ImpersonationXMLFilePath
      Path to a saved credential file that can be decoded by the current run time user. This file will need to contain a user and password at the very least
.PARAMETER ImpersonationUserName
      If impersonation is needed the supply the user name  for the account that has the impersonation RBAC role
.PARAMETER ImpersonationPassword
      If impersonation is needed the supply the password of the user name  for the account that has the impersonation RBAC role
.PARAMETER ImpersonationDomain
      If impersonation is needed you can optionally supply the domain for the account that has the impersonation RBAC role 
.PARAMETER EWSManagedApiPath
      The path to the EWS Managed API, if none is specified then the default is "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll" 
.PARAMETER ExchangeVersion
      Version of Exchange to pass to the creation of the EWS service, if none is specified then the default will be "Exchange2010_SP2"
.PARAMETER EwsUrl
      Specify the EWS URL, if none is specified then Auto Discover is used.
.PARAMETER EmailErrorsTo
      The Email address(es) to send any error reports or script run time error reports too
.PARAMETER EmailErrorsFrom
      The Email address any error reports or script run time error reports are sent from
.PARAMETER SMTPServer
      The SMTP server used to send any error reports
.PARAMETER EWSTracing
      Enables EWS tracing if needed
.PARAMETER IgnoreSSLCertificate
      Sets the EWS connection to ignore any SSL errors
.EXAMPLE
      PS C:\> .\Sync-EWSCalendarOneWay.ps1 –SourceMailbox Joe.Doe@Company.com –DestinationMailbox Jane.Doe@Company.com –TimeToSyncInDays 365 –StartingDate 01/01/2013
–ImpersonationUserName ImpService –ImpersonationPassword Password1 –ImpersonationDomain CORP
–EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
–ExchangeVersion Exchange2010_SP2 –EwsUrl https://webmail.susq.com/EWS/Exchange.asmx -EmailErrorsTo HelpDesk@company.com
–EmailErrorsFrom ScriptReports@company.com –SMTPServer mail.company.com

Description
-----------
Syncs all the calendar entries found between 01/01/2013 12:00AM and 365 days in the future (01/01/2014 12:00AM) in the source mailbox with the SMTP address of
Joe.Doe@Company.com to the destination mailbox with the SMTP address of Jane.Doe@Company.com. The sync is done through an account that has the impersonation RBAC
role and it’s username, password, and domain are supplied. The path for the EWS API has been specified along with the version of Exchange to work with. Any
errors encountered during the run time of the script will be sent to HelpDesk@company.com from ScriptReports@company.com using the SMTP server mail.company.com
.EXAMPLE
PS C:\> .\Sync-EWSCalendarOneWay.ps1 –SourceMailbox Joe.Doe@Company.com –DestinationMailbox Jane.Doe@Company.com –TimeToSyncInDays 365 –StartingDate 01/01/2013
-ImpersonationXMLFilePath C:\Cred.xml –EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
–ExchangeVersion Exchange2010_SP2 –EwsUrl https://webmail.susq.com/EWS/Exchange.asmx -EmailErrorsTo HelpDesk@company.com –EmailErrorsFrom ScriptReports@company.com
–SMTPServer mail.company.com

Description
-----------
Syncs all the calendar entries found between 01/01/2013 12:00AM and 365 days in the future (01/01/2014 12:00AM) in the source mailbox with the SMTP address of
Joe.Doe@Company.com to the destination mailbox with the SMTP address of Jane.Doe@Company.com. The sync is done through an account that has the impersonation RBAC
role and an XML file holding the credentials of the impersonation account is used. The path for the EWS API has been specified along with the version of Exchange
to work with. Any errors encountered during the run time of the script will be sent to HelpDesk@company.com from ScriptReports@company.com using the SMTP server
mail.company.com
.INPUTS
None
.OUTPUTS
None
.NOTES
Author: John Mello
Date: September 17 2013
#>

[CmdletBinding(DefaultParameterSetName="Default")]
Param(
[Parameter(Position=0,Mandatory=$True)]
[string]$SourceMailbox,

[Parameter(Position=1,Mandatory=$True)]
[string]$DestinationMailbox,

[Parameter(Position=2,Mandatory=$false)]
[ValidateRange(1,730)]
[int]$TimeToSyncInDays = 730,

[Parameter(Position=3,Mandatory=$false)]
[DateTime]$StartingDate = (Get-Date),

[Parameter(Position=4,Mandatory=$False)]
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[String]$ImpersonationUserName,

[Parameter(Position=4,Mandatory=$False,ParameterSetName="ImpersonationFile")]
[ValidateScript({Test-Path $_ })]
[String]$ImpersonationXMLFilePath,

[Parameter(Position=5,Mandatory=$False)]
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[String]$ImpersonationPassword,

[Parameter(Position=6,Mandatory=$False)]
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[String]$ImpersonationDomain,

[Parameter(Position=7,Mandatory=$False)]
[ValidateScript({Test-Path $_ })]
[String]$EWSManagedApiPath = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll",

[Parameter(Position=8,Mandatory=$False)]
[String]$ExchangeVersion = "Exchange2010_SP2",

[Parameter(Position=9,Mandatory=$False)]
[String]$EwsUrl,

[Parameter(Position=10,Mandatory=$False)]
[String[]]$EmailErrorsTo,

[Parameter(Position=11,Mandatory=$False)]
[String]$EmailErrorsFrom,

[Parameter(Position=12,Mandatory=$False)]
[String]$SMTPServer,

[Parameter(Position=13,Mandatory=$False)]
[switch]$EWSTracing,

[Parameter(Position=14,Mandatory=$False)]
[switch]$IgnoreSSLCertificate

)

#Region Helper Functions

Function Send-ErrorReport {
<# .SYNOPSIS Used to create a one line method to write an error warning to the console, send an error email, and exit a script when an terminal error is encountered .DESCRIPTION Send-ErrorReport Takes a Subject and message body field and uses the Subject to write a warning messages to the console and as the email subject. It uses the body as the body of the email that will be sent. You can also specify and SMTP Server, From, and To address or set the default options. Once complete the script sends the exit command to script calling the function .PARAMETER Subject The subject of the email to be sent and the warning message that is sent to the console .PARAMETER body The body of the email sent .PARAMETER HaltScript Sends the Exit command to the script caling the function, used to report on terminating errors .EXAMPLE PS C:\powershell> Send-ErrorReport -Subject "can't load EWS module" -Body "can't load EWS module, verify this path : $EWSManagedApiPath" -HaltScript

WARNING: can't load EWS module

------------------
Description
------------------

This will send an email through the specifed SMTP server, from and to the specifed addresses with the specifed subject and body and use the sbubject to
write a warning message. Then function will stop the script that called it
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[string]$Subject,

[Parameter(Position=1,Mandatory=$True)]
[string]$body,

[Parameter()]
[switch]$HaltScript
)

Write-Warning $Subject
#Appened Script name to email Subject
$Subject = "Set-TechCalendar.ps1 : " + $Subject
send-mailmessage -from $EmailErrorsFrom -to $EmailErrorsTo -smtpserver $SMTPServer -subject $Subject -Body $body -BodyAsHtml
If ($HaltScript) {Exit}
}

Function New-ErrorTableEntry {
<# .SYNOPSIS Returns a error table object .DESCRIPTION Creates a PSObject with the strings provided and returns it .PARAMETER Error At what step the error occured .PARAMETER Detail Item that the error occured on or the actual error .EXAMPLE PS C:\powershell> New-ErrorTableEntry -Error "Deleting Calendar Entry" -Detail "This Calendaer entry"

------------------
Description
------------------

This will return the a table entry with the specifed information
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[string]$Error,

[Parameter(Position=1,Mandatory=$True)]
[String]$Detail
)
$Entry = New-Object PSObject -Property @{
Error = $Error
Detail = $Detail
}
Return $Entry
}

Function Get-EWSCalendarSearchResults {
<# .SYNOPSIS Returns all the the Calender entries from a specifed search range .DESCRIPTION Given a starting and ending searach range along with the and EWS Service object and EWS folder ID, the Function will search for and return all the entires within that range .PARAMETER StartRange A start range in DateTime format .PARAMETER EndRange An end range in DateTime format .PARAMETER EWSService The EWS Service object that will be searched .PARAMETER EWSCalFolder The EWS Folder object that the search results will be returned from .EXAMPLE PS C:\powershell> Get-EWSCalendarSearchResults -StartRange "01/01/2013" -EndRange "01/01/2014" -EWSService $SomeUserEWSService -EWSCalFolder $EWSCalendarFolder

------------------
Description
------------------

This will return and EWS object that uses impersonation with a specifed URL
#>

[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[DateTime]$StartRange,

[Parameter(Position=1,Mandatory=$True)]
[DateTime]$EndRange,

[Parameter(Position=2,Mandatory=$True)]
[Object]$EWSService,

[Parameter(Position=3,Mandatory=$True)]
[Object]$EWSCalFolder
)

#Create the range to search and return up to 1000 items
$Calview = new-object Microsoft.Exchange.WebServices.Data.CalendarView($StartRange,$EndRange,1000)
#Use the search to pull create a result set
$CalSearchResult = $EWSService.FindAppointments($EWSCalFolder.id,$Calview)
#if more items are available then double the search range and try again until no more items are left
While ($CalSearchResult.MoreAvailable) {
$Calview.MaxItemsReturned = ($Calview.MaxItemsReturned * 2)
$CalSearchResult = $EWSService.FindAppointments($EWSCalFolder.id,$Calview)
}
Return $CalSearchResult
}

#EndRegion Helper Functions

#Region Load Dependencies
Write-Verbose "Loading EWS Managed API"
Try{
Import-Module -Name $EWSManagedApiPath -ErrorAction Stop
}
Catch {
Send-ErrorReport -Subject "Can't load EWS module (Sync-EWSCalendarOneWay.PS1)" -Body "Please verify this path : $EWSManagedApiPath
Full error is as follows:
$_" -HaltScript
}
#EndRegion Load Dependencies

#Region Variable Creation
#Create Table to Hold errors
$ErrorTable = @()

#Pull the search range in days specifed by $TimeToSyncInDays, the maximum search range in EWS is 2 years
#12AM was choosen as the Startdate since we wanted to correctly capture any changes made during the day
Write-Verbose "Creating Search range with the start time of $StartingDate and $TimeToSyncInDays days in the future"
[DateTime]$Today = $StartingDate.ToLongDateString() + " 12:00 AM"
[DateTime]$Future = ((Get-Date).Adddays($TimeToSyncInDays)).ToLongDateString() + " 12:00 AM"

#Load saved credential file if needed
If ($ImpersonationXMLFilePath) {
Write-Verbose "Impersonation credential file specifed, importing login info”
Try {
$ImportCreds = Import-Clixml $ImpersonationXMLFilePath -ErrorAction Stop
$NewCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $ImportCreds.UserName, ($ImportCreds.Password | ConvertTo-SecureString -Erroraction Stop) -ErrorAction Stop
}
Catch {
Send-ErrorReport -Subject "Issue using the specified Impersonation credential file (Sync-EWSCalendarOneWay.PS1)" -Body "

Please verify that the runtime account being used can access and decode the credential file


Runtime User: $ENV:UserName
FIlePath: $ImpersonationXMLFilePath
Full error is as follows:
$($_.Exception)" -HaltScript
}
$ImpersonationUserName= $NewCreds.GetNetworkCredential().UserName
$ImpersonationPassword = $NewCreds.GetNetworkCredential().Password
$ImpersonationDomain = $NewCreds.GetNetworkCredential().Domain
}

#Create Folder ID for the well know folder 'Calenadar', used to pull the calendar folder for each mailbox
$FolderID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)

#Create EWS Service object
Try {
If ($EWSTracing) {
Write-Verbose "EWS Tracing enabled"
$EWSservice.traceenabled = $true
}
if ($IgnoreSSLCertificate){
Write-Verbose "Ignoring any SSL certificate errors"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };
}
Write-Verbose "Creating EWS Service object"
$EWSService = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion) -ErrorAction Stop
Write-Verbose "Checking if the runtime or a seperate account will be used for impersonation"
If ($ImpersonationUserName -and $ImpersonationPassword) {
Write-Verbose "Secondary account for Impersonation specifed ($ImpersonationUserName)"
If ($ImpersonationDomain) {
#If a domain is presented then use that as well
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword,$ImpersonationDomain) -ErrorAction Stop
}
Else {
#Otherwise leave the domain blank
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword) -ErrorAction Stop
}
}
Else{
Write-Verbose "Runtime account specifed for impersonation ($ENV:Username)"
$EWSService.UseDefaultCredentials = $true
}
If ($EwsUrl) {
Write-Verbose "Using the specifed EWS URL of $EwsUrl"
$EWSService.URL = New-Object Uri($EwsUrl) -ErrorAction Stop
}
}
Catch{
Send-ErrorReport -Subject "Can't create EWS Service (Sync-EWSCalendarOneWay.PS1)" -Body "Please verify this path : $EWSManagedApiPath
Full error is as follows:
$_" -HaltScript
}

#Connect to each mailbox and pull calendar entries
Try{
Write-Verbose "Pointing EWS Service connection to the source mailbox ($SourceMailbox)"
$EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SourceMailbox) -ErrorAction Stop
If (-not $EwsUrl) {
Write-Verbose "Using the AutoDiscover to find the EWS URL"
$EWSService.AutodiscoverUrl($SMTPAddress, {$True})
}
$SourceCalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($EWSService,$FolderID)
$SourceSearchResults = Get-EWSCalendarSearchResults -StartRange $Today -EndRange $Future -EWSService $EWSService -EWSCalFolder $SourceCalendarFolder

Write-Verbose "Pointing EWS Service connection to the destination mailbox ($DestinationMailbox)"
$EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $DestinationMailbox) -ErrorAction Stop
If (-not $EwsUrl) {
Write-Verbose "Using the AutoDiscover to find the EWS URL"
$EWSService.AutodiscoverUrl($SMTPAddress, {$True})
}
$DestinationCalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($EWSService,$FolderID)
$DestinationSearchResults = Get-EWSCalendarSearchResults -StartRange $Today -EndRange $Future -EWSService $EWSService -EWSCalFolder $DestinationCalendarFolder
}
Catch {
$body = "

Verify the following info:


Source Mailbox: $SourceMailbox
Destination Mailbox: $DestinationMailbox
If using impersonation or an EWS url check that as well
Full error is as follows:
$_"
Send-ErrorReport -Subject "Can't bind to a calender (Sync-EWSCalendarOneWay.PS1)" -Body $body -HaltScript
}

#EndRegion Variable Creation

#Region Comparison Work
#If items were found in the date range then compare the list
If ($DestinationSearchResults.count -or $SourceSearchResults.count) {
Write-Verbose "Items found in at least one calendar, creating compare list"
$Comparelist = Compare-Object -ReferenceObject $DestinationSearchResults -DifferenceObject $SourceSearchResults -Property Subject,Start,End,Location,IsAllDayEvent,LegacyFreeBusyStatus
}
Else {
#No entires found, both calendars are blank
$body = "

Verify the following info:


Check runtime account or impersonation account
Source Mailbox: $SourceMailbox
Destination Mailbox: $DestinationMailbox
Search Range: $TimeToSyncInDays"
Send-ErrorReport -Subject "Both Calendars are empty (Sync-EWSCalendarOneWay.PS1)" -Body $body -HaltScript
}

Write-Verbose "Seperating the differences into an Add and Delete list"
$Adds = $Comparelist | Where-Object {$_.SideIndicator -eq "=>"}
$Deletes = $Comparelist | Where-Object {$_.SideIndicator -eq "<="} #Work on the new appts, if any #Note that the EWSService should still be set to the destination mail box, which was accessed last #but we double check just to be sure if (-not $EWSService.ImpersonatedUserId.Id -eq $DestinationMailbox) { $EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $DestinationMailbox) } If ($Adds) { Write-Verbose "$($Adds.count) Calendar entries found only in the soruce mailbox, adding to the destination calendar" foreach ($NewAppt in $Adds) { $EWSCalObjectCopy = New-Object Microsoft.Exchange.WebServices.Data.Appointment($EWSService) $EWSCalObjectCopy.Subject = $NewAppt.Subject $EWSCalObjectCopy.Location = $NewAppt.Location $EWSCalObjectCopy.Start = $NewAppt.Start $EWSCalObjectCopy.End = $NewAppt.End $EWSCalObjectCopy.IsAllDayEvent = $NewAppt.IsAllDayEvent $EWSCalObjectCopy.LegacyFreeBusyStatus = $NewAppt.LegacyFreeBusyStatus $EWSCalObjectCopy.IsReminderSet = $false Try {$EWSCalObjectCopy.Save()} Catch { Write-Warning "Can't create calendar entry with the subject : $($EWSCalObjectCopy.Subject), logging" $ErrorTable += (New-ErrorTableEntry -Error "Error creating Calender Entry" -Detail "Subject = $($EWSCalObjectCopy.Subject), Start = $($EWSCalObjectCopy.Start), End = $($EWSCalObjectCopy.End)") } } } Else {Write-Verbose "After comparison no adds have been found"} #Work on the removed appts, if any If ($Deletes) { Write-Verbose "$($Deletes.count) Calendar entries found only in the destination mailbox, deleting from the destination calendar" foreach ($DeletedAppt in $Deletes) { #Create the range to search and return up to 10 items $MatchingAppts = Get-EWSCalendarSearchResults -StartRange $DeletedAppt.Start -EndRange $DeletedAppt.End -EWSService $EWSService -EWSCalFolder $DestinationCalendarFolder #Check if any results were found If ($MatchingAppts) { #In case of multiple entries use Istem fount and delete $ItemFoundAndDeleted = $false #Compare all entries found and if there is a match delete that entry and move onto the next appt on the delete list Foreach ($FoundAppt in ($MatchingAppts)) { If (($FoundAppt.subject -eq $DeletedAppt.subject) -and ($FoundAppt.Location -eq $DeletedAppt.Location) -and ($FoundAppt.Start -eq $DeletedAppt.Start) -and ($FoundAppt.End -eq $DeletedAppt.End) -and ($FoundAppt.IsAllDayEvent -eq $DeletedAppt.IsAllDayEvent) -and ($FoundAppt.LegacyFreeBusyStatus -eq $DeletedAppt.LegacyFreeBusyStatus)) { Try { #Item Found, doing a hard delete (Not sent to recovery folder) $FoundAppt.Delete([Microsoft.Exchange.Webservices.Data.DeleteMode]::HardDelete) #Set item found to true so we don't search the rest of the results $ItemFoundAndDeleted = $True } Catch { Write-Warning "Can't delete Calendar Entry with the subject : $($FoundAppt.Subject), logging" $ErrorTable += (New-ErrorTableEntry -Error "Error Deleting Calender Entry" -Detail "Subject = $($FoundAppt.Subject), Start = $($FoundAppt.Start), End = $($FoundAppt.End)") } } If ($ItemFoundAndDeleted) {Break} } } Else { Write-Verbose "Can't find entry with the subject : $($DeletedAppt.Subject), logging" $ErrorTable += (New-ErrorTableEntry -Error "Error finding Calendar Entry to delete" -Detail "Subject = $($FoundAppt.Subject), Start = $($FoundAppt.Start), End = $($FoundAppt.End)") } } } Else {Write-Verbose "After comparison no deletes have been found"} #Used only to show the script is working in tidal If ($Adds) { If ($Adds.count) {Write-Host "$($Adds.count) new entries added"} Else {Write-Host "1 new entries added"} } Else {Write-Host "0 new entries added"} If ($Deletes) { If ($Deletes.count) {Write-Host "$($Deletes.count) entries deleted"} Else {Write-Host "1 entries deleted"} } Else {Write-Host "0 entries deleted"} #EndRegion Comparison Work #Region Error Reporting #If any errors enteringm, finding, or deleting emails then send a report If ($ErrorTable) { $HTMLBody = @"

"@
Write-verbose "Erros found, creating table and emailing report"
$HTMLBody += $ErrorTable |
Select-Object Error, Detail |
Sort-Object Error |
ConvertTo-HTML -body "

Full Error Report
"
If ($ErrorTable.Count) {$Subject = "$($ErrorTable.Count) Errors found in Sync-EWSCalendarOneWay.PS1"}
Else {$Subject = "1 Errors found in Sync-EWSCalendarOneWay.PS1"}
send-mailmessage -from $EmailErrorsFrom -to $EmailErrorsTo -smtpserver $smtpServer -subject $Subject -Body ($HTMLBody | Out-String) -BodyAsHtml
}

#EndRegion Error Reporting

Posted in EWS, Exchange 2010, PowerShell | Leave a comment

Leave a Reply

  • Archives

  • October 2013
    M T W T F S S
    « Jul   Dec »
     123456
    78910111213
    14151617181920
    21222324252627
    28293031  
  • Page list