1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
| <#
.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<BR>Full error is as follows:<BR>$_" -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 "<H4>Please verify that the runtime account being used can access and decode the credential file</H4><BR><B>Runtime User: </B>$ENV:UserName<BR><B>FIlePath: </B>$ImpersonationXMLFilePath<BR><B>Full error is as follows:</B><BR>$($_.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<BR>Full error is as follows:<BR>$_" -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 = "<H4>Verify the following info:</h4><BR><B>Source Mailbox: </B>$SourceMailbox<BR><B>Destination Mailbox: </B> $DestinationMailbox<BR>If using impersonation or an EWS url check that as well<BR><B>Full error is as follows:</B><BR>$_"
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 = "<h4>Verify the following info:</H4><BR>Check runtime account or impersonation account<BR><B>Source Mailbox: </B>$SourceMailbox<BR><B>Destination Mailbox: </B>$DestinationMailbox<BR><B>Search Range: </B>$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 = @"
<style>
BODY{
background-color:grey;font-family:Tahoma}
"font-family:Tahoma
}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;Font-Size:9pt}
TH{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:lightblue}
TD{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:lightgrey}
</style>
"@
Write-verbose "Erros found, creating table and emailing report"
$HTMLBody += $ErrorTable |
Select-Object Error, Detail |
Sort-Object Error |
ConvertTo-HTML -body "<H5>Full Error Report</H5>"
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 |
You must be logged in to post a comment.