Exchange.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
#region Types
add-type @'
namespace CPolydorou.Exchange
{
    public class GroupMembership
    {
        public string Group;
        public string Object;
        public bool Member;
        public string GroupDN;
        public string ObjectDN;
    }
}
'@

#endregion

#region Functions

#region Get-PublicFolderReplicationStatus
function Get-PublicFolderReplicationStatus
{
    <#
        .SYNOPSIS
        Checks the replication status of Exchange Public Folders.
 
        .DESCRIPTION
        The Get-PublicFolderReplicationStatus cmdlet checks the item count of a Public Folder and it's subfolders on two replicas and compares the item count on each folder.
     
        .PARAMETER TopLevelPublicFolder
        Specifies the path to the Public folder.
 
        .PARAMETER ReferenceServer
        Specifies the name of the server that is going to be used as source.
 
        .PARAMETER DifferenceServer
        Specifies the name of the server that is going to be compared to the source server.
 
        .PARAMETER IncompleteOnly
        When this parameter is used, only the Public Folders with different item counts are displayed.
 
        .INPUTS
        None. You cannot pipe objects to Get-PublicFolderReplicationStatus
 
        .OUTPUTS
        Get-PublicFolderReplicationStatus creates a table that contains the paths of the Public folders and the item count on each server.
 
        .EXAMPLE
        Get-PublicFolderReplicationStatus -TopLevelPublicFolder "\PublicFolder" -ReferenceServer ExchangeServer1 -DifferenceServer ExchangeServer2 -IncompleteOnly
 
        This command will compare the item count of the "PublicFolder" public folder and it's subfolders on the ExchangeServer1 and ExchangeServer2 servers and will display only the folder where the item count is not the same.
 
        .NOTES
        This is an one way check. In order to verify the replication, please run the same command using the refference server as source and vice versa.
    #>


    Param
    (
        [string]$TopLevelPublicFolder,
        [string]$ReferenceServer,
        [string]$DifferenceServer,
        [switch]$IncompleteOnly
    )

    Begin {}

    Process
    {

        # Get the public folders from both servers
        $publicfoldersref = Get-PublicFolder -ResultSize unlimited -Recurse -Server $ReferenceServer -Identity $TopLevelPublicFolder 
        $publicfoldersdif = Get-PublicFolder -ResultSize unlimited -Recurse -Server $DifferenceServer -Identity $TopLevelPublicFolder 

        foreach($pf in $publicfoldersref)
        {
            # TODO
            # Test if public folder exists on both servers

            # Compare statistics
            $StatisticsRef = Get-PublicFolderStatistics -Identity $pf.Identity -Server $ReferenceServer -ResultSize unlimited
            $StatisticsDif = Get-PublicFolderStatistics -Identity $pf.Identity -Server $DifferenceServer -ResultSize unlimited

            $obj = New-Object psobject
            $obj | Add-Member -MemberType NoteProperty -Name Parent -Value $pf.ParentPath
            $obj | Add-Member -MemberType NoteProperty -Name Name -Value $pf.Name
            $obj | Add-Member -MemberType NoteProperty -Name ReferenceCount -Value $StatisticsRef.itemcount
            $obj | Add-Member -MemberType NoteProperty -Name DifferenceCount -Value $StatisticsDif.itemcount

            if( $IncompleteOnly )
            {
                if( $StatisticsRef.ItemCount -ne $StatisticsDif.ItemCount)
                {
                    $obj
                }
                else
                {
                    continue
                }
            }
            else
            {
                $obj
            }
        }
    }

    End {}
}
#endregion

#region Get-SendOnBehalfPermission
Function Get-SendOnBehalfPermission
{
    <#
        .SYNOPSIS
        Gets the recipients that have send on behalf permission.
 
        .DESCRIPTION
        The Get-SendOnBehalfPermission cmdlet returns a list of all the recipients that have Send On Behalf permission.
     
        .PARAMETER Identity
        The Identity of the recipient on which the permissions are set.
    #>


    Param
    (
        [Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter]$Identity
    )

    $recipient = Get-Recipient $Identity

    if($recipient.recipienttype -like "*Mailbox")
    {
        $delegates = (Get-Mailbox $recipient.Identity).GrantSendOnBehalfTo
        $delegates |
            Get-Recipient
    }

    if($recipient.recipienttype -like "*Group")
    {
        $delegates = (Get-DistributionGroup $Recipient.Identity).GrantSendOnBehalfTo
        $delegates |
            Get-Recipient
    }
}
#endregion

#region New-TerminationInboxRule
Function New-TerminationInboxRule
{
<#
    .SYNOPSIS
    Creates a new termination inbox rule.
 
    .DESCRIPTION
    The New-TerminationInboxRule cmdlet creates an inbox rule that replies to everyone that sends a message on the mailbox.
     
    .PARAMETER Identity
    The identity of the mailbox
 
    .PARAMETER URL
    The EWS URL, usually is https://mail.domain.com/EWS/Exchange.asmx. If not specified, autodiscover will be used.
 
    .PARAMETER Credential
    The credentials to use. If not specified, the currently logged on user's credentials will be used. These credentials must belong to
    a user that has impersonation rights on the mailbox.
 
    .PARAMETER MessageSubject
    The subject of the reply.
 
    .PARAMETER MessageBody
    The body of the message.
 
    .PARAMETER RuleName
    The name of the rule to be created.
 
    .EXAMPLE
    [PS] C:\Windows\system32>New-TerminationInboxRule -Identity cpolydorou@lab.local -URL https://exchange2013a.lab.local/ews/exchange.asmx -RuleName "TestRule" -MessageSubject "Test Rule Subject" -MessageBody "Test Rule Body."
 
    [PS] C:\Windows\system32>Get-InboxRule -Mailbox cpolydorou
 
    Name Enabled Priority RuleIdentity
    ---- ------- -------- ------------
    TestRule True 1 2163278858382475265
#>


    [CmdletBinding()]
    Param
    (
        [Parameter(Position = 0, Mandatory = $true)]
        [string]$Identity,

        [Parameter(Position = 1, Mandatory = $false)]
        [string]$URL,

        [Parameter(Position = 2, Mandatory = $false)]
        [PSCredential]$Credential,

        [Parameter(Position = 3, Mandatory = $true)]
        [string]$MessageSubject,

        [Parameter(Position = 4, Mandatory = $true)]
        [string]$MessageBody,

        [Parameter(Position = 5, Mandatory = $true)]
        [string]$RuleName = "Termination Auto Reply"
    )

    # Load Managed API dll
    try
    {
        Add-Type -Path ($psscriptroot + "\Microsoft.Exchange.WebServices.dll")
        Write-Verbose "EWS API Loaded."
    }
    catch
    {
        Write-Error "Could not locate the EWS API."
        return
    }

    # Get the mailbox
    try
    {
        $m = Get-Mailbox $Identity
    }
    catch
    {
        throw ("Could not find mailbox " + $Identity)
    }

    # Get the primary smtp address
    $PrimarySMTPAddress = $m.PrimarySMTPAddress

    # Set Exchange Version
    $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013 

    # Create Exchange Service Object
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion) 

    # Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
    if($Credential)
    {
        #Credentials Option 1 using UPN for the windows Account
        $creds = New-Object System.Net.NetworkCredential($Credential.UserName.ToString(),$Credential.GetNetworkCredential().password.ToString())    
        $service.Credentials = $creds
        Write-Verbose ("Using provided credentials (" + $Credential.UserName.ToString() + ").")
    }
    else
    {   
        #Credentials Option 2
        $service.UseDefaultCredentials = $true    
        Write-Verbose "Using current account."
    }

    if( $URL )
    {
        #CAS URL Option 1 Hardcoded
        $uri=[system.URI] $URL    
        $service.Url = $uri
        Write-Verbose ("Using CAS Server: " + $Service.url)
    }
    else
    {     
        #CAS URL Option 1 Autodiscover
        $service.AutodiscoverUrl($PrimarySMTPAddress,{$true})    
        Write-Verbose "Using Autodiscover."
    }

    # Set impersonation
    $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$PrimarySMTPAddress); 

    # Create the message template
    $templateEmail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
    $templateEmail.ItemClass = "IPM.Note.Rules.ReplyTemplate.Microsoft"
    $templateEmail.IsAssociated = $true
    $templateEmail.Subject = $MessageSubject
    $templateEmail.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody($MessageBody)
    $PidTagReplyTemplateId = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65C2, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
    $templateEmail.SetExtendedProperty($PidTagReplyTemplateId, [System.Guid]::NewGuid().ToByteArray())
    try
    {
        $templateEmail.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
        Write-Verbose "Created the message template."
    }
    catch
    {
        Write-Error ("Could not create the template:" + $_.Exception.Message)
        return
    }

    #Create Inbox Rule
    $inboxRule = New-Object Microsoft.Exchange.WebServices.Data.Rule
    $inboxRule.DisplayName = $RuleName
    $inboxRule.IsEnabled = $true
    $inboxRule.Conditions.SentToOrCcMe = $true
    $inboxRule.Actions.ServerReplyWithMessage = $templateEmail.Id
    $createRule = New-Object Microsoft.Exchange.WebServices.Data.CreateRuleOperation[] 1
    $createRule[0] = $inboxRule
    try
    {
        $service.UpdateInboxRules($createRule,$true)
        Write-Verbose "Successfully created the inbox rule."
    }
    catch
    {
        Write-Error ("Could not create the inbox rule: " + $_.Exception.Message)
        return
    }
}
#endregion

#region Test-DistributionGroupMember
Function Test-DistributionGroupMember
{
    <#
    .SYNOPSIS
 
    Test if an object is member of a distribution group.
    .DESCRIPTION
 
    The Test-DistributionGroupMember function will check if an object is member of a distribution group.
    .PARAMETER DistributionGroup
 
    The distribution group to check against.
    .PARAMETER Object
 
    The object to check.
     
    .PARAMETER Recurse
 
    Check for membership recursively
 
    .EXAMPLE
 
    Test-DistributionGroupMember -DistributionGroup distributionGroup -Object userEmail
     
    .EXAMPLE
 
    Get-DistributionGroup | Test-DistributionGroupMember -DistributionGroup distributiongroup@lab.local
 
    This command will get all the distribution groups and check if they are members of the distributiongroup@lab.local group.
 
    .EXAMPLE
 
    Get-Mailbox | Test-DistributionGroupMember -DistributionGroup distributiongroup@lab.local -Recurse
 
    This command will get all the mailboxes and check if they are members of the distributiongroup@lab.local group recursively (via nested groups).
 
    #>


    Param
    (
        [parameter(Mandatory=$true,Position=0)]
        [string]$DistributionGroup,

        [parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [string[]]$Object,

        [parameter(Mandatory=$false,Position=2)]
        [switch]$Recurse
    )

    Begin {}

    Process
    {
        foreach($o in $Object)
        {
            # Get the distribution group
            $group = New-Object PSObject
            try
            {
                $group = Get-DistributionGroup $DistributionGroup -ErrorAction Stop
            }
            catch
            {
                Write-Error ("Could not find the distribution group " + $DistributionGroup)
                return $null
            }

            # Get the recipient
            $recipient = New-Object PSObject
            try
            {
                $recipient = Get-Recipient $o -ErrorAction stop
            }
            catch
            {
                Write-Error ("Could not find a recipient for " + $o)
                return $null
            }

            # Query Active Directory
            $objectdn = $recipient.distinguishedname
            $groupdn = $group.distinguishedname
            if($Recurse)
            {
                $query = "(&(DistinguishedName=$objectdn)(memberOf:1.2.840.113556.1.4.1941:=$groupdn))"
            }
            else
            {
                $query = "(&(DistinguishedName=$objectdn)(memberof=$groupdn))"
            }
            # Query Active Directory
            $results = ([adsisearcher]$query).findall() 

            # Create the custom object
            $obj = New-Object CPolydorou.Exchange.GroupMembership
            $obj.Group = $group.Name
            $obj.Object = $recipient.Name

            if($results.Count -eq 0)
            {
                $obj.Member = $false
            }
            else
            {
                $obj.Member = $true
            }

            # Add the DNs of the group and the object
            $obj.GroupDN = $groupdn
            $obj.ObjectDN = $objectdn

            Write-Output $obj
        }
    }

    End {}
}
#endregion

#region Connect-Exchange
Function Connect-Exchange
{
    [cmdletbinding(DefaultParameterSetName=’SnapIn’)]
    
    Param
    (
        [parameter(Mandatory=$false, ParameterSetName = "SnapIn")]
        [switch]$SnapIn,

        [parameter(Mandatory=$false, ParameterSetName = "Implicit")]
        [switch]$Implicit,

        [parameter(Mandatory=$false, ParameterSetName = "Implicit")]
        [string]$Server = $env:COMPUTERNAME,

        [parameter(Mandatory=$false, ParameterSetName = "Script")]
        [switch]$Script
    )

        # if no switches have been selected connect using implicit remoting
        if($PSCmdlet.MyInvocation.BoundParameters.Count -eq 0)
        {
            $Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri ("http://" + $Server + "/PowerShell") -Authentication Kerberos 
            Import-Module (Import-PSSession -Session $Session -DisableNameChecking) -Global -DisableNameChecking
            return
        }

        # Connect by adding the snapin
        if($SnapIn)
        {
            Add-PSSnapin *exchange*
            return
        }

        # Connect by implicit remoting
        if($Implicit)
        {
            $Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri ("http://" + $Server + "/PowerShell") -Authentication Kerberos 
            Import-Module (Import-PSSession -Session $Session -DisableNameChecking) -Global -DisableNameChecking
            return
        }

        # Connect using the RemoteExchange.ps1 script
        if($Script)
        {
            # Get the path of the exchange installation folder
            #TODO: should check for versions later than 15 (2013) here
            $ExInstall = ""
            try
            {
                $ExInstall = (get-itemproperty HKLM:\SOFTWARE\Microsoft\ExchangeServer\V15\Setup).MsiInstallPath
            }
            catch
            {
                Write-Error "Could not locate the excange home directory."
                return
            }
            $scriptPath = $ExInstall + 'bin\RemoteExchange.ps1'
            . $scriptPath
            Connect-ExchangeServer -auto
            return
        }
}
#endregion

#region Move-ActiveMailboxDatabaseToPreference
Function Move-ActiveMailboxDatabaseToPreference
{
    <#
    .SYNOPSIS
 
    Activate Mailbox Database Copies using ActivationPreference.
    .DESCRIPTION
 
    The Move-ActiveMailboxDatabaseToPreference function will activate a database copy using it's activation preference number.
    .PARAMETER Server
 
    The name of the database.
 
    .PARAMETER TargetActivationPreference
 
    The activation preference number of the copy to be activated.
    .PARAMETER ShowOnly
 
    Only show the changes, not perform them.
    .EXAMPLE
 
    Move-ActiveMailboxDatabaseToPreference -Database DB001 -TargetActivationPreference 2
 
    This command will activate the copy of the database DB001 that has ActivationPreference 2.
    #>


    [cmdletbinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = 'High'
    )]

    Param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true, Position=0)]
        [Alias('Name')] 
        [String[]]
        $Database,

        [Parameter(Mandatory=$true,ValueFromPipeline=$false, Position=1)] 
        [int]$TargetActivationPreference,

        [switch]$ShowOnly
    )

    Begin{}

    Process
    {
        foreach($db in $Database)
        {
            if($PSCmdlet.ShouldProcess($db))
            {
                # Get the mailbox database
                New-Variable database -Force
                try
                {
                    $Database = Get-MailboxDatabase $db

                    # Get the database copies
                    $Copies = $database | Get-MailboxDatabaseCopyStatus

                    # Get the mounted copy
                    $mountedCopy = $Copies | Where-Object {$_.Status -eq "Mounted"}

                    # Find the copy we want to activate using the activation preference
                    $copyToActivate = $Copies | Where-Object {$_.ActivationPreference -eq $TargetActivationPreference}

                    # Check if the copy to activate exiss
                    if($copyToActivate -ne $null)
                    {
                        # Check the health of the copy and if it is lagged
                        if($copyToActivate.Status -ne "Healthy")
                        {
                            Write-Error "The copy to be activated is not in a healthy state."
                        }

                        if($copyToActivate.ReplayLagStatus -like "*Enabled:True*")
                        {
                            Write-Error "The copy to be activated is a lagged copy."
                        }

                        if($ShowOnly)
                        {
                            Write-Warning ("The copy " + $copyToActivate.Identity + " (ActivationPreference:" + $copyToActivate.ActivationPreference + ") will be activated.")
                        }
                        else
                        {
                            # Activate the copy
                            Move-ActiveMailboxDatabase -Identity $Database.Identity -ActivateOnServer $copyToActivate.MailboxServer
                        }
                    }
                    else
                    {
                        Write-Error "There is no database copy with preference $TargetActivationPreference for database $db"
                        continue
                    }
                }
                catch
                {
                    Write-Error "Could not find database $db."
                    continue
                }
            }
        }
    }

    End{}

}
#endregion

#region Rename-ExchangeShell
Function Rename-ExchangeShell
{
    <#
    .SYNOPSIS
 
    Set the title on the Exchange Shell window.
    .DESCRIPTION
 
    Set the title on the Exchange Shell window.
    .PARAMETER Title
 
    The new title.
    .EXAMPLE
 
    Rename-ExchangeShell -Title "Mailbox Query"
 
    This command will rename the current Exchange Shell to "Mailbox Query"
    #>


    Param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Title
    )

    # Form the prompt function as a string
    $promptFunction = 'Function Global:Prompt{ $host.UI.RawUI.WindowTitle = "' + $Title + '"; Write-Host "[PS] " -NoNewLine -ForegroundColor Yellow; Write-Host (Get-Location).Path -NoNewLine; ">"}'

    # Create a scriptblock from that string
    $sb = [scriptblock]::Create($promptFunction)

    # Invoke the scriptblock
    Invoke-Command -ScriptBlock $sb
}
#endregion

#region Get-SendConnectorDomains
Function Get-SendConnectorDomains
{
    <#
    .SYNOPSIS
 
    Get the domains on each send connector.
    .DESCRIPTION
 
    The Get-SendConnectorDomains function will return all the domain names on each send connector and the respective cost.
    .PARAMETER Identity
 
    The identity of the connector to examine. If not specified, all connectors will be examined.
    .EXAMPLE
    Get-SendConnectorDomains
 
    This command will return all the domains configured on all send connectors.
 
    .EXAMPLE
    Get-SendConnectorDomains -Identity Internet
 
    This command will return all the domains configured on the "Intenet" send connector.
 
    .EXAMPLE
    Get-SendConnector -Identity "Test" | Get-SendConnectorDomains
 
    This command will return all the domains configured on the "Test" send connector.
    #>


    [cmdletBinding()]

    Param
    (
        [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$Identity
    )

    Begin
    {
        # Check if Exchange cmdlets are available
        try
        {
            Get-Command "Get-SendConnector" -ErrorAction Stop |
                Out-Null
        }
        catch
        {
            Throw "Could not find the Exchange cmdlets."
        }    
    }

    Process
    {
        # Get the send connectors
        Write-Verbose "Getting the send connectors"
        $connectors = @()

        # Get specific send connectors
        if($Identity)
        {
            foreach($sc in $Identity)
            {
                $connectors += Get-SendConnector -Identity $sc
            }
        }
        # Get all send connectors
        else
        {
            $connectors = Get-SendConnector
        }

        # Process each send connector
        foreach($sendC in $connectors)
        {
            Write-Verbose ("Processing send connector " + $sendC.Identity)

            # Get the string representation of the address space
            try
            {
                # This call will not fail if we are using implicit remoting
                $addressspacestring = $sendC.AddressSpaces.Split(',') 
            }
            catch
            {
                # if the above command fails, we are using the exchange shell
                # or have loaded the exchange snap in or binaries
                # Since the address spaces is an object, we are going to construct
                # the string representation
                $addressspacestring = @()
                $sendC.AddressSpaces |
                %{
                    $addressspacestring += $_.Type + ":" + $_.Address + ";" + $_.Cost
                }
            }

            # Parse each address space string and create custom objects
            $addressspacestring |
                %{
                    $start = $_.IndexOf(":") + 1
                    $end = $_.IndexOf(";")

                    $obj = New-Object -TypeName PSObject -Property @{
                                                                    'Domain' = $_.Substring($start, $end - $start)
                                                                    'Send Connector' = $sendC.Identity
                                                                    'Cost' = $_.Substring($end + 1, $_.Length - $end - 1)
                                                                   }

                    Write-Output $obj
                } |
                    Select-Object -Property 'Domain','Send Connector','Cost' |
                        Sort-Object -Property Domain
        }
    }

    End {}
}
#endregion

#region Get-MailboxDatabaseCopyThatShouldBeActive
Function Get-MailboxDatabaseCopyThatShouldBeActive
{
    <#
    .SYNOPSIS
 
    Get the mailbox database copies that have been moved from their home server.
    .DESCRIPTION
 
    The Get-MailboxDatabaseCopyThatShouldBeActive function will return all the mailbox database copies that are active and have an ActivationPreference value greater that 1.
    .PARAMETER Activate
 
    Activate the copies
    .EXAMPLE
 
    Get-MailboxDatabaseCopyThatShouldBeActive -Activate
 
    This command will get all the copies that should be activated and prompt to confirm the activation.
    #>


    [cmdletBinding(
        SupportsShouldProcess=$true,
        ConfirmImpact="High"
    )]

    Param
    (
        [switch]$Activate
    )

    Begin
    {
        # Check if Exchange cmdlets are available
        # Check for exchange cmdlets here
        try
        {
            Get-Command "Get-MailboxServer" -ErrorAction Stop |
                Out-Null
            Write-Verbose "Exchange cmdlets are available."
        }
        catch
        {
            Throw "Exchange cmdlets are not available. Please use the Exchange Management Shell."
        }
    }

    Process
    {
        # Examine all database copies
        Write-Verbose "Getting mailbox database copies."        
        $copies = Get-MailboxServer |
                    %{
                        Write-Verbose ("`tGetting copies from server " + $_.Name)
                        Get-MailboxDatabaseCopyStatus -Server $_.Name |
                            Where-Object { ($_.status -eq 'Mounted') -and ($_.ActivationPreference -gt 1)}
                    } |
                        %{
                            Get-MailboxDatabase $_.DatabaseName |
                                Get-MailboxDatabaseCopyStatus |
                                    Where-Object {$_.ActivationPreference -eq 1}                        
                        }

        # Prompt for activation
        if($Activate)
        {
            # Activate each copy
            foreach($c in $copies)
            {
                if ($PSCmdlet.ShouldProcess($c.Databasename, "Move-ActiveMailboxDatabase -ActivateOnServer " + $c.MailboxServer))
                {
                    Move-ActiveMailboxDatabase $c.DatabaseName -ActivateOnServer $c.MailboxServer |
                        Select-Object -ExcludeProperty RunspaceID  
                }
            }
        }
        else
        {
            # Return the copies
            $copies
        }
    }

    End {}
}
#endregion

#region Test-ExchangeImpersonation
function Test-ExchangeImpersonation
{
    <#
    .Synopsis
    Test the Exchange impersonation rights on a mailbox.
    .DESCRIPTION
    Test the Exchange impersonation rights on a mailbox.
    .EXAMPLE
        PS C:\> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateDraft -Verbose -EWSUrl "https://mail.lab.local/ews/exchange.asmx"
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using EWS Url.
        VERBOSE: Creating message in drafts.
     
        Create an item in the test.mailbox@lab.local mailbox.
 
    .EXAMPLE
        PS C:\Users\administrator.LAB\Desktop> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateSubfolder -Verbose
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using autodiscover.
        VERBOSE: Creating subfolder "Impersonation Test" in Inbox.
 
        Create the folder "Impersonation Test" in the test.mailbox Inbox folder.
 
    .EXAMPLE
        PS C:\> Test-ExchangeImpersonation -PrimarySMTPAddress test.mailbox@lab.local -Credential $cred -Action CreateDraft -Verbose -EWSUrl "https://mail.lab.local/ews/exchange.asmx"
        VERBOSE: Importing EWS library.
        VERBOSE: Using supplied credentials.
        VERBOSE: Connecting using EWS Url.
        VERBOSE: Creating message in drafts.
        Exception calling "Save" with "1" argument(s): "The request failed. The remote server returned an error: (401) Unauthorized."
        At C:\Users\administrator.LAB\Desktop\ModuleTesting\CPolydorou.Exchange\Exchange.psm1:986 char:29
        + $message.Save([Microsoft.Exchange.WebServices.Data.W ...
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
            + FullyQualifiedErrorId : ServiceRequestException
 
        The user does not have permission to impersonate.
 
    #>


    [CmdletBinding()]
    Param
    (
        # The primary SMTP address of the target mailbox
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $PrimarySMTPAddress,

        # The credentials of the account with the impersonation rights
        [Parameter(Mandatory=$true,
                   Position=1)]
        $Credential,

        # The action to perform
        [Parameter(Mandatory=$true,
                   Position=2)]
        [ValidateSet('ListInboxItems','CreateSubfolder','CreateDraft','SendMessage')]
        $Action = "ListInboxItems",
        
        # The EWS URL
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
        [Alias('Url')]
        $EWSUrl,

        # The recipient of the test message (used with action "SendMessage")
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
        $Recipient
    )

    Begin
    {
        # Import the dll
        Write-Verbose "Importing EWS library."
        try
        {
            Add-Type -Path ($psscriptroot + "\Microsoft.Exchange.WebServices.dll")
        }
        catch
        {
            Throw "Could not load the EWS API."
            return
        }

        # Set Exchange Version
        $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013 

        # Create Exchange Service Object
        $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion) 

        # Configure the credentials
        if($Credential)
        {
            Write-Verbose "Using supplied credentials."
            $service.Credentials = New-Object System.Net.NetworkCredential($Credential.UserName.ToString(),$Credential.GetNetworkCredential().password.ToString())    
        }
        else
        {
            Write-Verbose "Using credentials from prompt."
            $c = Get-Credential
            $service.Credentials = New-Object System.Net.NetworkCredential($credential.UserName.ToString(),$c.GetNetworkCredential().password.ToString())    
        }
    }

    Process
    {
        # Set the EWS url
        try
        {
            if($EWSUrl)
            {
                Write-Verbose "Connecting using EWS Url."
                $service.Url = [system.URI] $EWSUrl
            }
            else
            {
                Write-Verbose "Connecting using autodiscover."
                $service.AutodiscoverUrl($PrimarySMTPAddress,{$true})
            }
        }
        catch
        {
            Throw $_
            return
        }
        # Set impersonation
        $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$PrimarySMTPAddress)

        switch ($Action)
        {
            'ListInboxItems' {
                                # Get messages in inbox
                                $properties = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.ItemSchema]::Id,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayTo,
                                                                                                         [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)

                                $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView(50)
                                $view.PropertySet = $properties

                                do
                                {    
                                    $findResults = $service.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $view)
                                    foreach ($var in $findResults.Items)
                                    {
                                        [Microsoft.Exchange.WebServices.Data.EmailMessage]$var |
                                            Select-Object -Property Id,DateTimeCreated,DisplayTo,Subject
                                    }
                                    $view.Offset = 50;
                                }
                                while ($findResults.MoreAvailable)
                             }
            'CreateDraft' {
                            Write-Verbose "Creating message in drafts."
                            $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
                            $message.Subject = "Test Impersonation"
                            $message.Body = "This is a test message created using impersonation."
                            $message.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Drafts)
                          }
            'CreateSubfolder' {
                                Write-Verbose 'Creating subfolder "Impersonation Test" in Inbox.'
                                # Create a folder in Inbox
                                $folder = New-Object Microsoft.Exchange.WebServices.Data.Folder($service)
                                $folder.DisplayName = "Impersonation Test";
                                $folder.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
                              }
            'SendMessage' {
                                # Send a message
                                if($Recipient -eq $null)
                                {
                                    Write-Error "Please specify a recipient."
                                    return
                                }

                                Write-Verbose "Sending a message to $Recipient."
                                $message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
                                $message.Subject = "Test Impersonation"
                                $message.Body = "This is a test message created using impersonation."
                                $message.ToRecipients.Add($Recipient);
                                $message.SendAndSaveCopy() |
                                    Out-Null
                              }
            Default {
                        Write-Verbose "No action specified"
                    }
        }
    }

    End
    {
    }
}
#endregion

#region Get-MailboxQuotaStatus
function Get-MailboxQuotaStatus
{
    <#
    .Synopsis
       Get the quota status for a mailbox.
 
    .DESCRIPTION
       Get the quota status for a mailbox.
 
    .EXAMPLE
        [PS] C:\>Get-MailboxQuotaStatus -Identity cpolydorou@lab.local
 
        Mailbox QuotaStatus
        ------- -----------
        Christos Polydorou NoChecking
         
        Get the quota status of mailbox cpolydorou@lab.local
 
    .EXAMPLE
       [PS] C:\>get-mailbox | Select-Object -First 2 | Get-MailboxQuotaStatus
 
        Mailbox QuotaStatus
        ------- -----------
        Administrator BelowLimit
        Christos Polydorou NoChecking
 
       Get the quota status of multiple mailboxes
 
    .EXAMPLE
        [PS] C:\>Get-MailboxQuotaStatus -Identity test.mailbox -Verbose
        VERBOSE: Mailbox Test Mailbox is following the database quotas.
 
        Mailbox QuotaStatus
        ------- -----------
        Test Mailbox BelowLimit
 
        Get verbose output
 
    .EXAMPLE
        [PS] C:\>Get-MailboxQuotaStatus -Identity test.mailbox | % Mailbox
 
        Name Alias ServerName ProhibitSendQuota
        ---- ----- ---------- -----------------
        Test Mailbox test.mailbox exchange2013a Unlimited
         
        The mailbox object is available as the "Mailbox" property of the cmdlet's output.
    #>


    [CmdletBinding()]
    Param
    (
        # The Identity of the mailbox
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string[]]$Identity
    )

    Begin
    {
        # Check for Exchange cmdlets
        try
        {
            Get-Command -Name "Get-Mailbox" -ErrorAction Stop |
                Out-Null
        }
        catch
        {
            Throw "Exchange cmdlets are not available."
        }

        # A function to convert the string value of the quota to a number
        function __quotaStringToNumber
        {
            Param
            (
                [string]$str
            )

            $startIndex = $str.IndexOf("(") + 1
            $stopIndex = $str.IndexOf(" bytes")
            $size = $str.Substring($startIndex, $stopIndex - $startIndex)
            $size
        }
    }

    Process
    {
        foreach($i in $Identity)
        {
            # Get the mailbox
            try
            {
                $mailbox = Get-Mailbox $i -ErrorAction Stop
            }
            catch
            {
                Write-Error "Could not find a mailbox for $i"
                continue
            }

            if($mailbox.UseDatabaseQuotaDefaults -eq $true)
            {   # The mailbox is using the database quotas
                #region Database Quotas
                Write-Verbose ("Mailbox " + $mailbox.Name + " is following the database quotas.")
                # Get the mailbox database
                $database = Get-MailboxDatabase $mailbox.Database

                if($database.IssueWarningQuota -eq "Unlimited" -and $database.ProhibitSendQuota -eq "Unlimited" -and $database.ProhibitSendReceiveQuota -eq "Unlimited")
                {
                    $quotaStatus = "NoChecking"
                }
                else
                {
                    # Save the values for the quota's
                    if($database.IssueWarningQuota.ToString() -eq "unlimited")
                    {
                        $warningQuota = [double]::MaxValue
                    }
                    else
                    {
                        $warningQuota = [double](__quotaStringToNumber -str $database.IssueWarningQuota.ToString())
                    }

                    if($database.ProhibitSendQuota.ToString() -eq "unlimited")
                    {
                        $prohibitSend = [double]::MaxValue
                    }
                    else
                    {
                        $prohibitSend = [double](__quotaStringToNumber -str $database.ProhibitSendQuota.ToString())
                    }

                    if($database.ProhibitSendReceiveQuota.ToString() -eq "unlimited")
                    {
                        $prohibitSendReceive = [double]::MaxValue
                    }
                    else
                    {
                        $prohibitSendReceive = [double](__quotaStringToNumber -str $database.ProhibitSendReceiveQuota.ToString())
                    }
                    #endregion
                }
            }
            else
            {   # The mailbox is not using the database quotas
                #region Mailbox Quotas
                Write-Verbose ("Mailbox " + $mailbox.Name + " is following the database quotas.")
                if($mailbox.IssueWarningQuota -eq "Unlimited" -and $mailbox.ProhibitSendQuota -eq "Unlimited" -and $mailbox.ProhibitSendReceiveQuota -eq "Unlimited")
                {
                    $quotaStatus = "NoChecking"
                }
                else
                {
                    # Save the values for the quota's
                    if($mailbox.IssueWarningQuota.ToString() -eq "unlimited")
                    {
                        $warningQuota = [double]::MaxValue
                    }
                    else
                    {
                        $warningQuota = [double](__quotaStringToNumber -str $mailbox.IssueWarningQuota.ToString())
                    }

                    if($mailbox.ProhibitSendQuota.ToString() -eq "unlimited")
                    {
                        $prohibitSend = [double]::MaxValue
                    }
                    else
                    {
                        $prohibitSend = [double](__quotaStringToNumber -str $mailbox.ProhibitSendQuota.ToString())
                    }

                    if($mailbox.ProhibitSendReceiveQuota.ToString() -eq "unlimited")
                    {
                        $prohibitSendReceive = [double]::MaxValue
                    }
                    else
                    {
                        $prohibitSendReceive = [double](__quotaStringToNumber -str $mailbox.ProhibitSendReceiveQuota.ToString())
                    }
                }
                #endregion
            }

            # Get the total size of the mailbox
            try
            {
                [double]$totalSize = __quotaStringToNumber -str ((Get-MailboxStatistics -Identity $mailbox.Identity).TotalItemSize)
            }
            catch
            {
                continue
            }
            #region size and quota compare
            if(-Not $quotaStatus)
            {
                if($totalSize -lt $warningQuota)
                {
                    $quotaStatus = "BelowLimit"
                }
                else
                {
                    if($totalSize -lt $prohibitSend)
                    {
                        $quotaStatus = "IssueWarning"
                    }
                    else
                    {
                        if($totalSize -lt $prohibitSendReceive)
                        {
                            $quotaStatus = "ProhibitSend"
                        }
                        else
                        {
                            $quotaStatus = "ProhibitSendReceive"
                        }
                    }
                }
            }
            #endregion

            # Create a custom object
            New-Object -TypeName psobject `
                       -Property @{
                                    "Mailbox" = $mailbox
                                    "QuotaStatus" = $quotaStatus
                                 }
        }
    }

    End
    {
    }
}
#endregion

#region Get-DistributionGroupMemberRecurse
function Get-DistributionGroupMemberRecurse
{
    <#
    .Synopsis
       Get the members of a distribution group.
    .DESCRIPTION
       Get the members of a distribution group.
    .EXAMPLE
        PS C:\> Get-DistributionGroupMemberRecurse -Identity "ExchangeAdministrators@lab.local" -Recurse
 
        Name RecipientType
        ---- -------------
        Administrator UserMailbox
        CPolydorou UserMailbox
    .EXAMPLE
        PS C:\> Get-DistributionGroup -Identity "ExchangeAdministrators@lab.local" | Get-DistributionGroupMemberRecurse -Recurse
 
        Name RecipientType
        ---- -------------
        Administrator UserMailbox
        CPolydorou UserMailbox
    #>


    [CmdletBinding(PositionalBinding=$false)]

    Param
    (
        # The group
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [string]
        $Identity,

        # Recursive query
        [Parameter()]
        [switch]
        $Recurse,

        # The server
        [Parameter(Mandatory=$false, 
                   Position=1)]
        [string]
        $Server

    )

    Begin
    {
        #region Load the Active Directory module
        try
        {
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        catch
        {
            Throw "Could not load the 'ActiveDirectory' module."
        }
        #endregion

        #region Test for Exchange cmdlets
        try
        {
            Get-Command "Get-Recipient" -ErrorAction Stop |
                Out-Null
        }
        catch
        {
            Throw "Could not find Exchange cmdlets."
        }
        #endregion

    }

    Process
    {
        #region Get the group
        $group = Get-DistributionGroup $Identity -ErrorAction Stop
        #endregion

        # The parameters for the command
        $params = @('-ResultSetSize', '$null')

        #region Set the query type (one level - recursive)
        if($Recurse)
        {
            $params += "-Filter"
            $params += "`"(memberOf -RecursiveMatch '$($group.DistinguishedName)')`""
        }
        else
        {
            $params += "-LDAPFilter"
            $params += "`"(memberof=$($group.distinguishedname))`""
        }
        #endregion

        #region Set the server
        if($Server)
        {
            $params += "-Server"
            $params += $Server
        }
        #endregion

        #region Execute the command
        $sb = [scriptblock]::Create("Get-ADObject " + $params)
        Invoke-Command -ScriptBlock $sb |
            %{
                try
                {
                    Get-Recipient $_.DistinguishedName -ErrorAction Stop
                }
                catch{}
            }
        #endregion
    }

    End
    {
    }
}
#endregion

#region Get-ExchangeSchemaVersion
function Get-ExchangeSchemaVersion
{
    <#
    .Synopsis
       Get the Exchange Schema version
    .DESCRIPTION
       Get the Exchange Schema and Objects versions
    #>


    [CmdletBinding()]

    Param ()

    Begin {}

    Process
    {
        # Get the domain
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

        # Connect to the Root DSE
        $root = [ADSI]"LDAP://RootDSE"

        # Get the domain dinstinguished name
        $domainDN = $root.Properties["defaultNamingContext"].Value

        # Connect to the configuration
        $configurationNamingContext = $root.configurationNamingContext

        # Get the version of the schema
        $SchemaVersion = ([ADSI]"LDAP://CN=ms-Exch-Schema-Version-Pt,cn=schema,$configurationNamingContext").Properties['RangeUpper'].Value

        # Get the version of the Exchange System Objects container
        $SystemObjectsVersion = ([ADSI]"LDAP://CN=Microsoft Exchange System Objects,$domainDN").Properties['objectVersion'].Value

        # Get the Exchange organizations and their version
        $organizations = ([ADSI]"LDAP://CN=Microsoft Exchange,CN=Services,$configurationNamingContext").Children
        foreach($o in $organizations)
        {
            $org = [ADSI]$o

            $name = $org.Properties['Name'].Value
            $version = $org.Properties['ObjectVersion'].Value

            $properties =  [ordered]@{
                                      "Domain" = $domain
                                      "Domain Distinguished Name" = $domainDN
                                      "Configuration Naming Context" = $configurationNamingContext.Value
                                      "Schema Version" = $SchemaVersion
                                      "Exchange System Objects Version" = $SystemObjectsVersion
                                      "Exchange Organization" = $name
                                      "Exchange Organization Version" = $version
                                      "Exchange Organization Distinguished Name" = $org.distinguishedName.Value
                                     }
            New-Object PSObject -Property $properties
        }
    }

    End {}
}
#endregion

#region Monitor-DatabaseCopyLogs
Function Monitor-MailboxDatabaseCopyLogs
{
    <#
    .Synopsis
       Monitor the mailbox database copy log status.
    .DESCRIPTION
       Monitor the mailbox database copy log status.
    .EXAMPLE
        Monitor the log copy and replay process on the exchange2013a server.
 
        PS C:\> Monitor-MailboxDatabaseCopyLogs -Server exchange2013a | ft
 
        TimeStamp LogsToCopy LogsToReplay LogCopyRate LogReplayRate
        --------- ---------- ------------ ----------- -------------
        4/12/2018 1:19:41 PM 0 21 0 0
        4/12/2018 1:19:47 PM 0 14 0 7
        4/12/2018 1:19:52 PM 0 4 0 10
    #>


    [cmdletBinding()]

    Param
    (
        # The server to check
        [Parameter(Mandatory=$false,Position=0,ParameterSetName='Server')]
        [string]
        $Server,

        # The database to check
        [Parameter(Mandatory=$false,Position=0,ParameterSetName='Database')]
        [string]
        $Database,

        # The internal between the checks
        [Parameter(Mandatory=$false,Position=1,ParameterSetName='Server')]
        [Parameter(Mandatory=$false,Position=1,ParameterSetName='Database')]
        [int]
        $Interval = 5
    )

    Begin
    {
        #region Check for Exchange cmdlets
        try
        {
            Get-Command "Get-MailboxDatabaseCopyStatus" -ErrorAction Stop | Out-Null
        }
        catch
        {
            Throw "Could not find the Exchange cmdlets."
        }
        #endregion
    }

    Process
    {
        #region Check for the Exchange server
        if($PSBoundParameters.ContainsKey("Server"))
        {
            try
            {
                $s = Get-ExchangeServer $Server -ErrorAction Stop

                if($s.ServerRole -notlike "*Mailbox*")
                {
                    Throw "The server $Server is not a mailbox server."
                }
            }
            catch
            {
                Throw "Could not find exchange server $server"
            }
        }
        #endregion

        #region Check for the database
        if($PSBoundParameters.ContainsKey("Database"))
        {
            try
            {
                Get-MailboxDatabase $Database -ErrorAction Stop | Out-Null
            }
            catch
            {
                Throw "Could not find database $Database"
            }
        }
        #endregion

        #region Monitor the logs

        # Mark the first loop
        $start = $true

        While($true)
        {
            # Save the previous replay log count
            $previousReplayCount = $replayCount

            # Get the replay log count
            if($Server)
            {
                $replayCount = (Get-MailboxDatabaseCopyStatus -Server $Server | Where-Object {$_.ReplayLagStatus -notlike "Enabled:True*"} | Measure-Object -Property ReplayQueueLength -Sum).Sum
            }
            else
            {
                $replayCount = (Get-MailboxDatabaseCopyStatus -Identity $Database | Where-Object {$_.ReplayLagStatus -notlike "Enabled:True*"} | Measure-Object -Property ReplayQueueLength -Sum).Sum
            }

            # Calculate the replay difference
            $replayDifference = $previousReplayCount - $replayCount

            # Save the previous copy log count
            $previousCopyCount = $copyCount

            # Get the copy log count
            if($Server)
            {
                $copyCount = (Get-MailboxDatabaseCopyStatus -Server $Server | Where-Object {$_.ReplayLagStatus -notlike "Enabled:True*"} | Measure-Object -Property CopyQueueLength -Sum).Sum
            }
            else
            {
                $copyCount = (Get-MailboxDatabaseCopyStatus -Identity $Database | Where-Object {$_.ReplayLagStatus -notlike "Enabled:True*"} | Measure-Object -Property CopyQueueLength -Sum).Sum
            }

            # Calculate the copy difference
            $copyDifference = $previousCopyCount - $copyCount
            
            # Chech if this is the first loop
            if($start)
            {
                $start = $false
                $copyDifference = 0
                $replayDifference = 0
            }

            # Create the properties for the custom object
            $props = [ordered]@{
                        TimeStamp = [datetime]::Now
                        LogsToCopy = $copyCount
                        LogsToReplay = $replayCount
                        LogCopyRate = $copyDifference
                        LogReplayRate = $replayDifference
                     }

            # Create the custom object
            New-Object PSObject -Property $props

            # Sleep
            Start-Sleep -Seconds $Interval
        }
        #endregion
    }

    End {}
}
#endregion
#endregion

#region Exports
Export-ModuleMember -Function Get-PublicFolderReplicationStatus
Export-ModuleMember -Function Get-SendOnBehalfPermission
Export-ModuleMember -Function New-TerminationInboxRule
Export-ModuleMember -Function Test-DistributionGroupMember
Export-ModuleMember -Function Connect-Exchange
Export-ModuleMember -Function Move-ActiveMailboxDatabaseToPreference
Export-ModuleMember -Function Get-MailboxDatabaseCopyThatShouldBeActive
Export-ModuleMember -Function Rename-ExchangeShell
Export-ModuleMember -Function Get-SendConnectorDomains
Export-ModuleMember -Function Test-ExchangeImpersonation
Export-ModuleMember -Function Get-MailboxQuotaStatus
Export-ModuleMember -Function Get-DistributionGroupMemberRecurse
Export-ModuleMember -Function Get-ExchangeSchemaVersion
Export-ModuleMember -Function Monitor-MailboxDatabaseCopyLogs
#endregion