-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerShell-EWS.psm1
1648 lines (1396 loc) · 50.8 KB
/
PowerShell-EWS.psm1
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Connect-EWS {
<#
.SYNOPSIS
Connects to a Exchange server throught EWS.
.DESCRIPTION
Connects to a Exchange server throught EWS.
.PARAMETER UserMailAddress
Specify the mailbox that you want to connect to a user account. You can use the followind values to identify the mailbox:
email address
.PARAMETER ModuleDllPath
Define the path of EWS module.
You must download and install him before
Download link: https://www.microsoft.com/en-eg/download/details.aspx?id=42951
.PARAMETER ServerVersion
Define ServerVersion if AutoDetect failed.
Possible value:
Exchange2007_SP1
Exchange2010
Exchange2010_SP1
Exchange2010_SP2
Exchange2013
Exchange2013_SP1
.PARAMETER EwsUrl
Define EWS Url if AutoDetect failed
.PARAMETER Credential
Define Credential who are authorized to read the mailbox
.EXAMPLE
PS C:\> $email = "[email protected]"
PS C:\> $credentials = @{
"Username" = $AuthUser;
"Password" = $password;
"Domain" = $Domain
}
PS C:\> $cred = New-Object -TypeName PSObject -Property $credentials
PS C:\> Connect-EWS -UserMailAddress $email -Credential $cred
.VERSION
1.0.0 - 2016.08.09
Initial version
1.1.0 - 2016.09.28
Change download EWS url
2.0.0 - 2016.10.06
Credential param is now [PSCredential]
To define Credential Just call Get-Credential
If UserMailAddress
.VALIDATION
Exchange 2013
.OUTPUTS
Microsoft.Exchange.WebServices.Data.ExchangeServiceBase
.NOTES
Additional information about the function.
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[ValidatePattern('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|^AutoDetect$')]
[Alias('MailAddress')]
[String]$UserMailAddress,
[Alias('DllPath')]
[String]$ModuleDllPath = "$env:SystemDrive\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll",
[ValidatePattern('^Exchange[0-9]{4}.{0,4}$|^AutoDetect$')]
[String]$ServerVersion = 'AutoDetect',
[ValidatePattern('^https?://[^/]*/ews/exchange.asmx$|^AutoDetect$')]
[Alias('Url')]
[String]$EwsUrl = "AutoDetect",
[Parameter(Mandatory = $true)]
[PSCredential]$Credential
)
Begin {
Try {
# Loading Module: Microsoft.Exchange.WebService ( if not loaded yet )
If (-not (Get-Module -Name:Microsoft.Exchange.WebServices)) {
Try {
Write-Debug -Message "Import Module $ModuleDllPath"
Import-Module -Name:$ModuleDllPath -ErrorAction:Stop
} Catch [System.IO.FileNotFoundException] {
Throw [System.IO.FileNotFoundException] "$_`nhttps://www.microsoft.com/en-eg/download/details.aspx?id=42951"
} Catch {
Throw [System.SystemException] "Loading module - $ErrorMessage"
}
}
if (!$UserMailAddress) {
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$UserMailAddress = [ADSI]"LDAP://<SID=$sid>"
}
# initializing EWS ExchangeService
If ($ServerVersion -eq "AutoDetect") {
Write-Debug -Message "ServerVersion is AutoDetect"
$ExchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
} Else {
Write-Debug -Message "ServerVersion is $ServerVersion"
$ExchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ServerVersion)
}
Write-Debug -Message "RequestedServerVersion: $($ExchangeService.RequestedServerVersion)"
Write-Debug -Message "UserAgent: $($ExchangeService.UserAgent)"
# Define Credential
$ExchangeService.Credentials = New-Object System.Net.NetworkCredential($Credential.UserName.ToString(), $Credential.GetNetworkCredential().password.ToString())
Write-Debug -Message "Credentials: $($ExchangeService.Credentials.Credentials.UserName)"
} Catch {
Write-Warning $_.Exception.GetType().FullName;
Throw [System.SystemException]$_.Exception.Message
}
}
Process {
Try {
# Define Autodiscover url
If ($EwsUrl -eq "AutoDetect") {
Write-Debug -Message "AutodiscoverUrl($UserMailAddress)"
$ExchangeService.AutodiscoverUrl($UserMailAddress)
} Else {
$ExchangeService.Url = New-Object Uri($EwsUrl)
}
Write-Debug -Message "EwsUrl: $($ExchangeService.Url)"
} Catch {
$ErrorMessage = $_.Exception.Message
$message1 = 'Exception calling "AutodiscoverUrl" with "1" argument\(s\): "Autodiscover blocked a potentially insecure redirection to'
$message2 = 'Exception calling "AutodiscoverUrl" with "1" argument\(s\): "The Autodiscover service returned an error."'
If ($ErrorMessage -match $message1) {
# When the credential is wrong (Username, Domain or password)
Throw [System.Security.Authentication.InvalidCredentialException] "Credential error"
} Elseif ($ErrorMessage -match $message2) {
# When the email address does not exist
Write-Error -Message "Email addresse does not exist($UserMailAddress)"
Throw [System.InvalidOperationException] "Email address does not exist"
} Else {
Throw [System.SystemException]$_.Exception.Message
}
}
}
End {
Try {
# try to list anything in mailbox to validate access
$rootFolderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot, $UserMailAddress)
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind([Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$ExchangeService, $rootFolderId) | out-null
Write-Debug -Message "Return ExchangeService"
Return [Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$ExchangeService
} Catch [System.Management.Automation.MethodInvocationException] {
$ErrorMessage = $_.Exception.Message
$message1 = "Exception calling `"Bind`" with `"2`" argument\(s\): `"The request failed. The remote name could not be resolved:"
If ($ErrorMessage -match $message1) {
# When the EWS url is wrong
$url = ($ErrorMessage -split "'")[1]
Throw [System.IO.IOException] "The remote name could not be resolved ($url)"
} Else {
Throw [System.SystemException]$_.Exception.Message
}
} Catch {
Throw [System.SystemException]$_.Exception.Message
}
}
}
function Get-EWSFolder {
<#
.SYNOPSIS
Returns a Folder object corresponding to the folder in a specified path.
.DESCRIPTION
Returns a Folder object corresponding to the folder in a specified path.
.PARAMETER MailboxName
Specify the mailbox that you want to connect to a user account. You can use the followind values to identify the mailbox:
email address
.PARAMETER Path
Enter the path of the folder
.PARAMETER WellKnownFolderName
Define the base search
.PARAMETER Service
Call Connect-EWS function
.PARAMETER List
A description of the List parameter.
.PARAMETER Credential
Define Credential who are authorized to read the mailbox (PSObject not PSCredential)
.EXAMPLE
PS C:\> $email = "[email protected]"
PS C:\> $credentials = @{
"Username" = $AuthUser;
"Password" = $password;
"Domain" = $Domain
}
PS C:\> $cred = New-Object -TypeName PSObject -Property $credentials
PS C:\> $service = Connect-EWS -UserMailAddress $email -Credential $cred -Verbose
PS C:\> Get-FolderEWS -MailboxName $email -Path "parent\child1\child11" -Service $service
.VERSION
1.0.0 - 2016.08.09
Initial Version
1.1.0 - 2016.09.26
Add List param to list all folder in define path
1.2.0 - 2016.09.29
Path param is not mandatory now, if is not setted you get WellKnown Folder Name
Add folder's Size even if there are children folder
1.3.0 - 2016.10.05
Remove MailboxName param & update $rootFolderId
.VALIDATION
Exchange 2013
.NOTES
Next release : Return Folder ID
#>
[CmdletBinding(ConfirmImpact = 'None')]
param
(
[Parameter(Mandatory = $false)]
[Alias('FullPath')]
[String]$Path = $null,
[ValidateSet('Calendar', 'Contacts', 'Inbox', 'SentItems', 'MsgFolderRoot', 'PublicFoldersRoot', 'Root', 'SearchFolders', 'ArchiveRoot', 'ArchiveMsgFolderRoot')]
[String]$WellKnownFolderName = "Inbox",
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service,
[Parameter(Mandatory = $false)]
[Switch]$List
)
Begin {
Try {
if ($Path) {
Write-Debug -Message "Try to search $Path"
# Split the path to search recursively
$arrPath = $Path.Split("\")
} Else {
Write-Debug -Message "Try to List Folder in $WellKnownFolderName"
}
# Initialize Variables
New-Variable -Name concatpath -Value ""
# Get all the folders in the message's root folder.
$rootFolderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::$WellKnownFolderName)
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $rootFolderId)
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Stop
}
}
Process {
Try {
# Represents the view settings in a folder search operation: maximum of returned folders = 1
$folderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1)
#Define Extended properties
$PR_FOLDER_PATH = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$PropertySet.Add($PR_FOLDER_PATH);
$folderView.PropertySet = $PropertySet;
if ($Path) {
if ($arrPath.count -eq 1) {
# Represents a search filter that determines wheter a property is equal to a given value or other property.
$searchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $Path)
$findFolderResults = $service.FindFolders($folder.Id, $searchFilter, $folderView)
If ($findFolderResults.TotalCount -gt 0) {
$folder = $findFolderResults.Folders[0]
$return = $true
Write-Debug -Message "Folder \$($folder.DisplayName) was found"
} Else {
Throw [System.IO.IOException] "Folder Not found"
}
} Elseif ($arrPath.count -gt 1) {
For ($i = 0; $i -lt $arrPath.count; $i++) {
# Represents a search filter that determines wheter a property is equal to a given value or other property.
$searchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $arrPath[$i])
$findFolderResults = $service.FindFolders($folder.Id, $searchFilter, $folderView)
If ($findFolderResults.TotalCount -gt 0) {
$folder = $findFolderResults.Folders[0]
$return = $true
$concatpath += "\$($arrPath[$i])"
Write-Debug -Message "Folder $concatpath was found"
} Else {
Throw [System.IO.IOException] "Folder Not found"
}
}
}
$folderPath = $null
# Properties is in ExtendedProperties
# To keep the value $item.ExtendedProperties.value
Write-Debug "Add Folder Path in Extended Properties"
$folder.TryGetProperty($PR_FOLDER_PATH, [ref]$folderPath) | Out-Null
} Else {
Write-Debug "The path is not define..."
}
} Catch [System.IO.IOException] {
Throw [System.IO.IOException] "Folder Not found"
} Catch {
Throw [System.SystemException]$_.Exception.Message
}
}
End {
Try {
if ($List) {
$folderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
#Define Extended properties
$PR_MESSAGE_SIZE_EXTENDED = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3592, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)
$PR_FOLDER_PATH = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(26293, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);
$psPropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$psPropertySet.Add($PR_MESSAGE_SIZE_EXTENDED);
$psPropertySet.Add($PR_FOLDER_PATH);
$folderView.PropertySet = $psPropertySet;
Try {
if ($Path) {
$folders = $service.FindFolders($findFolderResults.Id, $folderView)
} Else {
$folders = $service.FindFolders($folder.Id, $folderView)
}
if (($folders | Measure-Object).count -gt 0) {
$folders.Folders | ForEach-Object{
[Int]$folderSize = 0
#Deep Transval will ensure all folders in the search path are returned
$folderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep;
$findFolderResults = $service.FindFolders($_.Id, $folderView)
if (($findFolderResults | Measure-Object).count -eq 0) {
$_.TryGetProperty($PR_MESSAGE_SIZE_EXTENDED, [ref]$folderSize) | Out-Null
} Else {
(($findFolderResults.ExtendedProperties | Where-Object{ $_.PropertyDefinition.Tag -eq 3592 }).Value) | ForEach-Object{
$folderSize += $_
}
}
# Add folder size in properties in MB
$_ | Add-Member NoteProperty -Name "FolderSize(MB)" -Value ([Math]::Round($folderSize/1MB, 2, [MidPointRounding]::AwayFromZero)) -Force
}
}
} Catch [System.Management.Automation.MethodInvocationException]{
Write-Warning "Their is no folder"
} Catch {
Write-Error $_.Exception.Message
}
Return [Microsoft.Exchange.WebServices.Data.FindFoldersResults]$folders | Select-Object DisplayName, "FolderSize(MB)", ChildFolderCount, @{ Name = "MessageCount"; Expression = { $_.TotalCount } }
} Else {
Return [Microsoft.Exchange.WebServices.Data.Folder]$folder
}
} Catch {
Throw [System.SystemException]$_.Exception.Message
}
}
}
function Get-EWSMail {
<#
.SYNOPSIS
Use Get-MailEWS to view mail user.
.DESCRIPTION
Use Get-MailEWS to view mail user.
.PARAMETER GetFolder
Call Get-FolderEWS function
.EXAMPLE
PS C:\> $folder = Get-FolderEWS -MailboxName $email -FullPath "parent\child1\child11" -Service $service
PS C:\> Get-MailEWS -GetFolder $Folder
.VERSION
1.0.0 - 2016.08.09
Initial version
.VALIDATION
Exchange 2013
.OUTPUTS
System.Object
.NOTES
Limitation at 2000 item
#>
[OutputType([System.Object])]
Param
(
[Parameter(Mandatory = $True)]
[Microsoft.Exchange.WebServices.Data.ServiceObject]$Folder,
[Switch]$Full,
[Switch]$WithBody
)
Process {
Try {
Write-Debug -Message "$($Folder.DisplayName) - Retrieve mail list"
#list the first 2000 items who match
$mails = $Folder.FindItems(2000)
} Catch {
Write-Error -Message $_.Exception.Message
}
}
End {
Try {
if ($mails -ne 0) {
if ($WithBody) {
Write-Debug "Load Body"
$mails.load()
}
# Return mails
Write-Debug -Message "Return email object"
if ($Full) {
Return [System.Object]$mails
} Else {
if ($WithBody) {
Return [System.Object]$mails | Select-Object Subject, From, IsRead, IsAttachment, DateTimeReceived, DisplayTo, DisplayCC, @{ Name = "Body"; Expression = { $_.Body.text } } -
} Else {
Return [System.Object]$mails | Select-Object Subject, From, IsRead, IsAttachment, DateTimeReceived, DisplayTo, DisplayCC
}
}
} Else {
Throw [System.IO.IOException] "0 was founded"
}
} Catch [System.IO.IOException] {
Write-Warning -Message "0 mail was founded"
Return [System.Object]$mails
} Catch {
Write-Error -Message $_.Exception.Message
}
}
}
function Move-EWSMail {
<#
.SYNOPSIS
Move an email to another folder (in same mailbox)
.DESCRIPTION
Move an email to another folder (in same mailbox)
.PARAMETER Mail
put the mail you want to move, it's an EWS Object [System.Object]
ex: Get-MailEWS -GetFolder $Folder
.PARAMETER Destination
Define the destination folder, it's an EWS Object [Microsoft.Exchange.WebServices.Data.ServiceObject]
.PARAMETER Service
Call Connect-EWS function
.PARAMETER Test
Swith param define if Test mode is enable
.EXAMPLE
PS C:\> $EmailAddress = "[email protected]"
PS C:\> $service = Connect-EWS -UserMailAddress $EmailAddress -Credential $Credential
PS C:\> $Source = Get-FolderEWS -MailboxName $EmailAddress -FolderPath $SourcePath -Service $service
PS C:\> $mails = Get-MailEWS -GetFolder $Source
PS C:\> $limithour = 7
PS C:\> $Target = Get-FolderEWS -MailboxName $EmailAddress -FolderPath $DestPath -Service $service
PS C:\> Move-MailEWS -Mail $mails -TargetFolder $Target -Service $service -Hours $limithour -Test:$Test
.VERSION
1.0.0 - 2016.08.09
Initial version
.VALIDATION
Exchange 2013
.NOTES
Additional information about the function.
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[System.Object]$Mail,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ServiceObject]$Destination,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service,
[Switch]$Test
)
Process {
# If mail is not null, it means their is 1 or more mails
If ($Mail) {
$Mail | ForEach-Object{
try {
# Move the Message
If (-not $Test) {
Write-Debug -Message "Move $($_.Subject) to '$($Destination.FullPath)''"
$_.Move($Destination.Id)
} Else {
Write-Debug -Message "TEST - Move $($_.Subject) to '$($Destination.FullPath)''"
}
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Continue
}
}
} Else {
Write-Warning -Message "No email are moved"
}
}
}
function Remove-EWSMail {
<#
.SYNOPSIS
Use Remove-MailEWS cmdlet to delete existing email.
.DESCRIPTION
Use Remove-MailEWS cmdlet to delete existing email.
.PARAMETER Mail
Enter the email's you want to remove, it an email object
ex: Get-MailEWS -GetFolder $Folder
.PARAMETER Service
Call Connect-EWS function
.PARAMETER DeleteMode
Define the Delete mode.
By default it's a MoveToDeletedItems, but you select : HardDelete,MoveToDeletedItems,SoftDelete:
- The item or folder will be permanently deleted.
- The item or folder will be moved to the mailbox's Deleted Items folder.
- The item or folder will be moved to the dumpster. Items and folders in the dumpster can be recovered.
.PARAMETER Test
Swith param define if Test mode is enable
.EXAMPLE
PS C:\> Remove-MailEWS -Mail $mails -Service $service
.EXAMPLE
PS C:\> Remove-MailEWS -Mail $mails -Service $service -DeleteMode HardDelete
.VERSION
1.0.0 - 2016.08.09
Initial version
.VALIDATION
Exchange 2013
.NOTES
Delete mode: https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.deletemode(v=exchg.80).aspx
#>
Param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[psobject]$Mail,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service,
[ValidateSet('HardDelete', 'SoftDelete', 'MoveToDeletedItems')]
[String]$DeleteMode = "MoveToDeletedItems",
[Switch]$Test
)
Try {
# If mail is not null, it means their is 1 or more mails
If ($Mail) {
# Delete message
If (-not $test) {
[void]$Mail.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::$DeleteMode)
Write-Debug -Message "Delete $($Mail.Subject)"
} Else {
Write-Debug -Message "TEST - Delete $($Mail.Subject)"
}
} Else {
Write-Debug -Message "No email must be deleted"
}
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Continue
}
}
function Get-EWSCalendar {
<#
.SYNOPSIS
Retrieve a list of calendar from the GAL
.DESCRIPTION
Retrieve one or more calendar form the GAL (search with a wildcard...)
.PARAMETER CalendarName
Enter the name of the calendar. the value can be:
- Mailbox Name
- Mailbox Address
- Display Name
.PARAMETER Service
Call Connect-EWS function
.EXAMPLE
PS C:\> Get-CalendarEWS -CalendarName 'John Doe' -Service $Service
=> Retrieve all calendar who match with John Doe
.VERSION
1.0.0 - 2016.08.23
Initial version
.VALIDATION
Exchange 2013
.OUTPUTS
Array
.NOTES
For Calendar Query:
https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.resolvenamesearchlocation(v=exchg.80).aspx
.INPUTS
String, Microsoft.Exchange.WebServices.Data.ExchangeServiceBase
#>
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
[Alias('Calendar')]
[String]$CalendarName,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service
)
Begin {
Write-Debug -Message "Try to search $CalendarName"
[Array]$calendarArray = @()
}
Process {
Try {
# Search calendar, in GAL (Directory Only), with full details ($true)
$calendar = $Service.ResolveName($CalendarName, "DirectoryOnly", $true)
If ($calendar.count -ne 0) {
# If the number of calendar is greather than 0, we have more than 1 calendar
Write-Debug -Message "CalendarEWS - $($calendar.count) founded"
# Foreach calendar, add the mailbox Name & Address to the Contrat Properties
$calendar | ForEach-Object {
$Object = New-Object -TypeName PSObject
$Object = $_.Contact | Select-Object DisplayName, GivenName, CompanyName, ContactSource, Department, JobTitle, Manager, OfficeLocation, Surname, Culture, ExtendedProperties, Categories
$Object | Add-Member NoteProperty -Name MailboxName -Value $_.Mailbox.Name -Force
$Object | Add-Member NoteProperty -Name MailboxAddress -Value $_.Mailbox.Address -Force
$calendarArray += $Object
}
} Else {
Throw [System.AccessViolationException] "0 Calendar was founded"
}
} Catch [System.AccessViolationException]{
Throw [System.AccessViolationException] "0 Calendar was founded"
} Catch [System.Management.Automation.MethodInvocationException]{
$ErrorMessage = $_.Exception.Message
$message1 = "Exception calling `"ResolveName`" with `"3`" argument\(s\): `"The request failed. The remote name could not be resolved:"
If ($ErrorMessage -match $message1) {
# When the EWS url is wrong
$url = ($ErrorMessage -split "'")[1]
Throw [System.IO.IOException] "The remote name could not be resolved ($url)"
} Else {
Throw [System.SystemException] $_.Exception.Message
}
} Catch {
Write-Error -Message $_.Exception.Message
}
}
End {
Try {
# Return an Array beacause we may have 1 or more calendar
Return [Array]$calendarArray
} Catch {
Write-Error -Message $_.Exception.Message
}
}
}
function Get-EWSCalendarPermission {
<#
.SYNOPSIS
A brief description of the Get-EWSPermission function.
.DESCRIPTION
A detailed description of the Get-EWSPermission function.
.PARAMETER Path
Enter the path of the folder
.PARAMETER WellKnownFolderName
must remove some validateset ?
.PARAMETER Details
To show full details
.PARAMETER Service
Call Connect-EWS function
.EXAMPLE
PS C:\> Get-EWSPermission -Service $service
Name DisplayPermissionLevel
---- ----------------------
Default Reviewer
Anonymous FreeBusyTimeOnly
.EXAMPLE
PS C:\> Get-EWSPermission -Service $service -Details
Name : Default
PermissionLevel : Reviewer
Read : FullDetails
Edit : None
CreateItems : False
CreateSubFolders : False
DeleteItems : None
FolderOwner : False
FolderContact : False
FolderVisible : True
Name : Anonymous
PermissionLevel : FreeBusyTimeOnly
Read : TimeOnly
Edit : None
CreateItems : False
CreateSubFolders : False
DeleteItems : None
FolderOwner : False
FolderContact : False
FolderVisible : False
.VERSION
1.0.0 - First version
.NOTES
For more information about advanced functions, call Get-Help with any
of the topics in the links listed below.
#>
[CmdletBinding(ConfirmImpact = 'None')]
param
(
[Parameter(Mandatory = $false)]
[Switch]$Details,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service
)
Begin {
Try {
$Permissions = @()
# Get all the folders in the message's root folder.
$rootFolderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $rootFolderId)
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Stop
}
}
Process {
Try {
# On folder you can have many persmission
$folder.Permissions | ForEach-Object{
If ($_.UserId.PrimarySmtpAddress) {
$Name = $_.UserId.PrimarySmtpAddress
} else {
$Name = $_.UserId.StandardUser.ToString()
}
$_ | Add-Member NoteProperty -Name Name -Value $Name -Force
$Permissions += $_
}
} Catch {
Throw [System.SystemException]$_.Exception.Message
}
}
End {
Try {
if ($Details) {
Return $Permissions
} Else {
Return $Permissions | Select-Object Name, DisplayPermissionLevel
}
} Catch {
Throw [System.SystemException]$_.Exception.Message
}
}
}
function Set-EWSCalendarPermission {
<#
.SYNOPSIS
Define the level permission for a user or a group
.DESCRIPTION
Define the level permission for a user or a group
.PARAMETER UserAdress
ets the identifier of the user that the permission applies to.
.PARAMETER Permissionlevel
Sets the permission level.
.PARAMETER Service
Call Connect-EWS function
.PARAMETER Force
A description of the Force parameter.
.PARAMETER WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
.PARAMETER CanCreateItems
Gets or sets a value that indicates whether the user can create new items.
.PARAMETER CanCreateSubFolders
Sets a value that indicates whether the user can create subfolders.
.PARAMETER IsFolderOwner
Sets a value that indicates whether the user owns the folder.
.PARAMETER IsFolderVisible
Sets a value that indicates whether the folder is visible to the user.
.PARAMETER IsFolderContact
Sets a value that indicates whether the user is a contact for the folder.
.PARAMETER EditItems
Sets a value that indicates whether the user can edit existing items.
.PARAMETER DeleteItems
Sets a value that indicates whether the user can delete existing items.
.PARAMETER ReadItems
Sets the read items access permission.
.EXAMPLE
PS C:\> Set-EWSCalendarPermission -UserAdress [email protected] -Permissionlevel Editor -Service $service
.VERSION
1.0.0 - First version
1.1.0 - Add Custom Permission
.NOTES
https://msdn.microsoft.com/en-us/library/office/dn641962(v=exchg.150).aspx
https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.folderpermission_properties(v=exchg.80).aspx
#>
[CmdletBinding(DefaultParameterSetName = 'PermissionLevel',
ConfirmImpact = 'Medium')]
param
(
[Parameter(Mandatory = $true)]
[System.String]$UserAdress,
[Parameter(ParameterSetName = 'PermissionLevel',
Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.FolderPermissionLevel]$Permissionlevel,
[Parameter(Mandatory = $true)]
[Microsoft.Exchange.WebServices.Data.ExchangeServiceBase]$Service,
[Switch]$Force,
[Switch]$WhatIf,
[Parameter(ParameterSetName = 'CustomPermission')]
[Boolean]$CanCreateItems,
[Parameter(ParameterSetName = 'CustomPermission')]
[Boolean]$CanCreateSubFolders,
[Parameter(ParameterSetName = 'CustomPermission')]
[Boolean]$IsFolderOwner,
[Parameter(ParameterSetName = 'CustomPermission')]
[Boolean]$IsFolderVisible,
[Parameter(ParameterSetName = 'CustomPermission')]
[Boolean]$IsFolderContact,
[Parameter(ParameterSetName = 'CustomPermission')]
[Microsoft.Exchange.WebServices.Data.PermissionScope]$EditItems,
[Parameter(ParameterSetName = 'CustomPermission')]
[Microsoft.Exchange.WebServices.Data.PermissionScope]$DeleteItems,
[Parameter(ParameterSetName = 'CustomPermission')]
[Microsoft.Exchange.WebServices.Data.FolderPermissionReadAccess]$ReadItems
)
Begin {
Try {
# Get all the folders in the message's root folder.
$rootFolderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($Service, $rootFolderId)
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Stop
}
}
Process {
Try {
$folder.Permissions | ForEach-Object{
If ($_.UserId.PrimarySmtpAddress) {
$Name = $_.UserId.PrimarySmtpAddress
} else {
$Name = $_.UserId.StandardUser.ToString()
}
if ($Name -eq $UserAdress) {
if ($_.PermissionLevel -eq $Permissionlevel) {
$Status = 0
Return $Status | Out-Null
} else {
$Status = 1
$perm = $_
Return $Status | Out-Null
}
}
}
} Catch {
Write-Error -Message $_.Exception.Message -ErrorAction Stop
}
}
End {
Try {
# If Status :
# = 0 => User and permission still exist
# = 1 => User exist but the permission level is different
# Default => User not exist
switch ($status) {
'0' {
# the new permission level is the same
Write-Warning "The Permission still exist for this user"
Return
}
'1'{
if (!$Force) {
Write-Host "The Force parameter was not specified. If you continue, the permission level will be updated. Are you sure you want to continue?"
do {
$return = Read-Host "[Y] Yes [N] No (default is 'Y')"
} until ($return -eq "Y" -or $return -eq "N")
switch ($return) {
'N'{
Return
}
}
}
# the new permission is different
# Apply new permission
Write-Warning "The existing permission will be overriding"
Write-Debug "Remove existing Permission"
$folder.Permissions.Remove($perm) | Out-Null
}
default {
# User have no permission... Create new permission
Write-Debug "Create the permission for $UserAdress"
}
}
If (!$WhatIf) {
if ($PSCmdlet.ParameterSetName -ne "CustomPermission") {
$NewPermission = New-Object Microsoft.Exchange.WebServices.Data.FolderPermission($UserAddress, $Permissionlevel)
} Else {
$NewPermission = New-Object Microsoft.Exchange.WebServices.Data.FolderPermission
$NewPermission.UserId = $UserAddress
if ($CanCreateItems) {
$NewPermission.CanCreateItems = $CanCreateItems
}
if ($CanCreateSubFolders) {
$NewPermission.CanCreateSubFolders = $CanCreateSubFolders
}