ExchangePowerShell.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
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
# EP (ExchangePowerShell) Powershell Module 0.11.0
# Author: Pietro Ciaccio | LinkedIn: https://www.linkedin.com/in/pietrociaccio | Twitter: @PietroCiac
# Pre-requisites: Exchange Server 2016 Exchange Management Shell

# Checks if the powershell session has the Exchange 2016 powershell module loaded

if (!($env:ExchangeInstallPath)) {
    throw "Exchange Server system variable ExchangeInstallPath missing."
}

if ($env:ExchangeInstallPath -notmatch '\\V15\\') {
    write-warning "The Microsoft Exchange Management Shell will be loaded from '$($env:ExchangeInstallPath)'"
    write-warning "Exchange Server 2016 powershell module not detected. There may be issues."
}

try {
    $cmd = $null; $cmd = get-command 'get-mailbox' -erroraction stop
} catch {
    $invexpr = ". '$env:ExchangeInstallPath\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto -ClientApplication:ManagementShell"
    Invoke-Expression $invexpr
}

try {
    $cmd = $null; $cmd = get-command 'get-mailbox' -erroraction stop
} catch {
    throw "Unable to load the Microsoft Exchange Management Shell."
}

# Non Exchange specific functions and cmdlets
function Show {

    write-host ""
    write-host "EP (ExchangePowerShell) PowerShell Module 0.11.0" -foreground yellow
    #write-host ""
    write-host "Contribute via BTC: 1FjTBFdQEpfa1rRPCFTG74iDNrvdH5xU9K XRP: rhYuiuxpQLQoVtGrD52s79sGV5kApe5UqY"
    #write-host ""
    write-host "Please contact the author with any comments, issues, or requests for features and improvements via Twitter " -nonewline 
    write-host "@PietroCiac" -foreground white -nonewline
    write-host " or PowerShell Gallery."
    #write-host ""
    write-host "Please read the release notes for information on changes. Use Get-Help with cmdlets for guidance on usage."        
    write-host ""   

}

show

function Update-EPModule {
    <#
    .SYNOPSIS
        Checks for the latest module version on PSGallery.
 
    .DESCRIPTION
        Checks for the latest module version on PSGallery.
 
    #>


    Process {
        
        try {

            $FilePath = "$env:temp\EPModuleCheck.txt"
            $LastChecked = $null

            if (test-path $FilePath) {
                $LastChecked = (gi $FilePath).lastwritetime
            } else {
                new-item $FilePath -erroraction stop | out-null
                $LastChecked = (gi $FilePath).lastwritetime
            }

            $dateDiff = $null; $dateDiff = new-timespan $($LastChecked) $(get-date)

            if ($dateDiff.totaldays -ge 7) {
                $InstalledModuleVersion = $null
                try {
                    $InstalledModule = $null; $InstalledModule = Get-InstalledModule ExchangePowershell -erroraction stop
                    $InstalledModuleVersion = $InstalledModule.version.tostring()
                } catch {
                    $InstalledModuleVersion = "0.0.0"
                }
    
                $GalleryModule = $null; $GalleryModule = Find-Module exchangepowershell -Repository psgallery -erroraction stop
                $GalleryModuleVersion = $null; $GalleryModuleVersion = $GalleryModule.version.tostring()
    
                if ($GalleryModuleVersion -ne $InstalledModuleVersion) {
                    write-warning "EP module version $InstalledModuleVersion installed. $GalleryModuleVersion has been published to the PowerShell Gallery. Please update when possible."
                    write-host ""
                } else {
                    write-host "You are running the latest EP module version $InstalledModuleVersion."
                    write-host ""
                } 

                (gi $FilePath).lastwritetime = get-date
            }    

        } catch {
            
        }
    }

}

Update-EPModule

function Get-EPDate {
    <#
    .SYNOPSIS
        Checks date format for cmdlets.
 
    .DESCRIPTION
        Checks date format for cmdlets
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$false)][PSCustomObject]$Date
    )

    Process {        
        
        # validate date time
        if ($date.gettype().fullname -ne "System.DateTime") {
            try {
                $date = $date.tostring()
                if ($date -match "\D") {
                    throw "DateTime and numerical value formats supported only."
                }
                switch ($date.length) {
                    7           {$date = "0" + $date}
                    13          {$date = "0" + $date}
                    default     {}
                }
                switch ($date.length) {
                    8           {$date = [datetime]::ParseExact($date,'ddMMyyyy',$null)}
                    14          {$date = [datetime]::ParseExact($date,'ddMMyyyyHHmmss',$null)}
                    default     {throw "Unsupported date provided. Must be ddMMyyyy or ddMMyyyyHHmmss. E.g. 15112019150329 for 15th November 2019 15:03:29."}
                }
            } catch {
                throw $_.exception.message
            }
        }

        if ($date.gettype().fullname -ne "System.DateTime") {
            throw "'Date' format is unsupported. This must be of format System.DateTime or a string in the format of ddMMyyyy or ddMMyyyyHHmmss."
        }

        return $Date

    }
}

# Exchange Server functions and cmdlets
function Get-EPExchangeServer{
    <#
    .SYNOPSIS
        Checks an Exchange 2016 servers identity.
 
    .DESCRIPTION
        Checks an Exchange 2016 servers identity.
 
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity
    )

    Process {        
        
        # Validate Exchange Server
        if ($input) {
            if ($input.objectcategory.name -ne "ms-Exch-Exchange-Server"){
                throw "Unable to validate Exchange server identity."
            } else {
                $ExchangeServer = $null; $ExchangeServer = $input
            }
        }

        if (!($input)) {
            if ($identity.gettype().fullname -ne "System.String") {
                throw "Unable to use parameter 'Identity' of type '$($identity.gettype().fullname)'." 
            } else {
                try {
                    $ExchangeServer = $null; $ExchangeServer = Get-ExchangeServer -Identity $identity -erroraction stop
                } catch {
                    throw $_.exception.message
                }
            }
        }

        if ($ExchangeServer.Admindisplayversion.tostring() -notmatch "^version 15\." ) {
            write-warning "Exchange version is not 15 for '$($ExchangeServer.identity)'. There may be issues."
        }

        return $ExchangeServer
    }
}

function Start-EPRequiredServices {
    <#
    .SYNOPSIS
        Starts Exchange Server services that are required but are not running.
 
    .DESCRIPTION
        Starts Exchange Server services that are required but are not running. This cmdlet uses information from the Test-ServiceHealth cmdlet.
 
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
 
         
    .EXAMPLE
        Get-ExchangeServer Server1 | Start-EPRequiredServices
 
        This will start any required Exchange services that are not running on Server1.
 
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity
    )
    Process {     

        # Validate identity

        $ExchangeServer = $null
        try {
            if ($input) {            
                $ExchangeServer = $input | Get-EPExchangeServer
            } else {
                $ExchangeServer = Get-EPExchangeServer -Identity $Identity
            }
        } catch {
            throw $_.exception.message         
        }

        write-host "$($ExchangeServer.fqdn.toupper())." 

        try {
            $SH = $null; $SH = Test-ServiceHealth -server $($ExchangeServer.fqdn) -erroraction stop
            $NR = $null; $NR = ($SH.servicesnotrunning | sort-object -unique)
            if ($NR) {
                write-Warning "The following services are not running:"
                $NR
                write-host "Starting required services..."
                Invoke-Command -ComputerName $($ExchangeServer.fqdn) -ScriptBlock {$using:NR | start-service}
                write-host "Done."
            } else {
                write-host "All required services are running on $($ExchangeServer.fqdn.toupper())."
            }
        } catch {
            throw $_.exception.message
        }

    }
}

function Clear-EPExchangeLogs {
    <#
    .SYNOPSIS
        Clears Exchange Server 2016 logs older than a specified date.
 
    .DESCRIPTION
        Clears Exchange Server 2016 logs older than a specified date. Deletes files with extensions .log .blg and .etl. The cmdlet will determine the Exchange and IIS logging directories automatically.
 
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
 
    .PARAMETER StartDate
        Specify the date from which to clear logs. This can be of type Date.Time or a string in the format of ddMMyyyy or ddMMyyyyHHmmss.
     
    .EXAMPLE
        Get-ExchangeServer Server1 | Clear-EPExchangeLogs -Date (get-date).adddays(-30)
 
        This will clear logs older than 30 days on the Exchange server Server1.
 
    .EXAMPLE
        Clear-EPExchangeLogs -Identity Server2 -Date 01112019
 
        This will clear logs older than the 1st November 2019 on the Exchange server Server2.
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$false)][PSCustomObject]$StartDate
    )
    Process {      
        
        # Validate identity

        $ExchangeServer = $null
        try {
            if ($input) {            
                $ExchangeServer = $input | Get-EPExchangeServer
            } else {
                $ExchangeServer = Get-EPExchangeServer -Identity $Identity
            }
        } catch {
            throw $_.exception.message         
        }

        # validate date time
        $Date = Get-EPDate -Date $StartDate

        # Script blocks
        $Scriptblock = $null; $Scriptblock = [scriptblock]::Create('
            Param($thisdate,$thisserver)
             
            $files = $null
            $scopecount = 0
            $successcount = 0
            $errorcount = 0
            $Status = $null
            $Comment = $null
 
            try {
                $ExchangeLoggingPath = $null; $ExchangeLoggingPath = $env:exchangeinstallpath + "Logging"
                $ExchangeTempUCPath = $null; $ExchangeTempUCPath = $env:exchangeinstallpath + "TransportRoles\data\Temp\UnifiedContent"
 
                if (test-path $ExchangeLoggingPath) {
 
                    $Files += [System.IO.Directory]::GetFiles($ExchangeLoggingPath,"*.log","AllDirectories")
                    $Files += [System.IO.Directory]::GetFiles($ExchangeLoggingPath,"*.blg","AllDirectories")
                    $Files += [System.IO.Directory]::GetFiles($ExchangeLoggingPath,"*.etl","AllDirectories")
                    $Files += [System.IO.Directory]::GetFiles($ExchangeTempUCPath,"*","AllDirectories")
 
                    $IISLoggingPath = $null;
                    try {
                        $IISLoggingPath = (get-iissite).logfile.directory
                    } catch {
                        throw "Unable to determine IIS logging paths."
                    }
                    if ($IISLoggingPath) {
                        $IISLoggingPath | . {process
                            {
                                $Files += [System.IO.Directory]::GetFiles([System.Environment]::ExpandEnvironmentVariables($_),"*.log","AllDirectories")
                            }
                        }
                    }
                } else {
                    throw "$ExchangeLoggingPath does not exist."
                }
     
                if ($Files) {
                    $Files | . {process
                        {
                            if ($([System.IO.File]::GetLastWriteTime($_)) -lt $thisdate) {
                                $scopecount += 1
                                try {
                                    [System.IO.File]::Delete($_)
                                    $successcount += 1
                                } catch {
                                    $errorcount += 1
                                }
                            }
                        }
                    }
                }
                $Status = "OK"
            } catch {
                $Status = "Error"
                $Comment += $_.exception.message
            }
 
            [pscustomobject]@{
                "Identity" = $thisServer
                "TotalFound" = $(($Files | measure).count)
                "InScope" = $scopecount
                "Deleted" = $successcount
                "Skipped" = $errorcount
                "Status" = $Status
                "Comment" = $null
            }
        '
)      

        # Local or Remote execution
        try {            
            $localhostname = (Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
            if ($localhostname -eq $ExchangeServer.fqdn) {
                try {
                    $scriptblock.invoke($date,$($ExchangeServer.fqdn))
                } catch {
                    throw $_.exception.message
                }
            } else {
                try {
                    Invoke-Command -ComputerName $($ExchangeServer.fqdn) -ScriptBlock $Scriptblock -ArgumentList $date,$($ExchangeServer.fqdn) -ErrorAction stop | select * -ExcludeProperty pscomputername,runspaceid
                } catch {
                    throw $_.exception.message
                }
            }            
        } catch {
            [pscustomobject]@{
                "Identity" = $($ExchangeServer.fqdn)
                "TotalFound" = 0
                "InScope" = 0
                "Deleted" = 0
                "Skipped" = 0
                "Status" = "Error"
                "Comment" = $_.exception.message
            }  
        } 
    }
}

function Get-EPMaintenanceMode {
    <#
    .SYNOPSIS
        Checks if a Microsoft Exchange Server 2016 computer is in maintenance mode.
  
    .DESCRIPTION
        Checks if a Microsoft Exchange Server 2016 computer is in maintenance mode.
           
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
  
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity
    )
    Process {  

        # Validate identity
        if ($input) {            
            $ExchangeServer = $null; $ExchangeServer = $input | Get-EPExchangeServer
        } else {
            $ExchangeServer = $null; $ExchangeServer = Get-EPExchangeServer -Identity $Identity
        }

        write-host "$($ExchangeServer.fqdn.toupper())." 

        # Determine DAG membership
        $isDAGMember = $false
        try {
            $RecipientServer = $null; $RecipientServer = Get-MailboxServer -identity $Exchangeserver.fqdn -erroraction stop
            if ($($RecipientServer | measure).count -ne 1) {
                throw "$($($RecipientServer | measure).count) servers returned from query. Unable to continue."
            }
            if ($RecipientServer.DatabaseAvailabilityGroup -ne $null) {
                $isDAGMember = $true
            }
        } catch {
            throw $_.exception.message
        } 

        try {
            # DAG members only
            if ($isDAGMember) {
                $MBServer = $null; $MBServer = $ExchangeServer | Get-MailboxServer -erroraction stop

                if ($MBServer.DatabaseCopyActivationDisabledAndMoveNow -eq $false) {
                    write-host "DatabaseCopyActivationDisabledAndMoveNow is False."
                } else {
                    write-warning "DatabaseCopyActivationDisabledAndMoveNow is True."
                }

                $cn = $null; $cn = invoke-command -ComputerName $($ExchangeServer.fqdn) -ScriptBlock {Get-ClusterNode $($using:ExchangeServer.fqdn)} -ErrorAction Stop
                if ($cn.state -eq "up") {
                    write-host "Cluster node is Up."
                } else {
                    write-warning "Cluster node is not Up."
                }

                if ($MBServer.DatabaseCopyAutoActivationPolicy -eq "unrestricted") {
                    write-host "DatabaseCopyAutoActivationPolicy is Unrestricted."
                } else {
                    write-warning "DatabaseCopyAutoActivationPolicy is $($MBServer.DatabaseCopyAutoActivationPolicy)."
                }

                $Copies = $null; $Copies = Get-MailboxDatabaseCopyStatus *\$($ExchangeServer.name) 
                if ($Copies) {
                    $Copies | . { process {
                        if ($_.status -notmatch "^healthy$|^mounted$") {
                            write-warning "$($_.name) database copy status is $($_.status)."
                        } else {
                            write-host "$($_.name) database copy status is $($_.status)."
                        }
                    }}
                }

                $CS = $null; $CS = Get-ServerComponentState -Identity $($ExchangeServer.fqdn) -erroraction stop | ? {$_.state -ne "active"}
                if (-not($CS)) {
                    write-host "Server component states active."
                } else {
                    write-warning "Server component states inactive: $($CS.component -join ';')"
                }

                write-host "Done."

            }
        } catch {
            throw $_.exception.message
        }
    }
}

function Enable-EPMaintenanceMode {
    <#
    .SYNOPSIS
        Puts a Microsoft Exchange Server 2016 computer into maintenance mode.
  
    .DESCRIPTION
        Puts a Microsoft Exchange Server 2016 computer into maintenance mode. CmdLet will -
          
            - drain queues
            - restart transport services
            - redirect messages to a redirection server
            - move off active database copies to an available DAG member
            - suspend the cluster node
            - prevent database activation on the server
            - suspend passive copies
            - set all server component states to inactive
  
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
  
    .PARAMETER RedirectionTarget
        Specify the identity of the computer you wish to redirect pending messages to.
          
    .PARAMETER MoveActiveDatabaseCopies
        Specify whether to move active database copies to other DAG members, if possible. The default is false.
  
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$false)][PSCustomObject]$RedirectionTarget,
        [switch]$MoveActiveDatabaseCopies
    )
    Process {        

        # Validate identity
        if ($input) {            
            $ExchangeServer = $null; $ExchangeServer = $input | Get-EPExchangeServer
        } else {
            $ExchangeServer = $null; $ExchangeServer = Get-EPExchangeServer -Identity $Identity
        }

        # Validate Redirection Server
        $RedirectionServer = $null; 
        if ($RedirectionTarget) {
            try {
                $RedirectionServer = Get-EPExchangeServer -Identity $RedirectionTarget
            } catch {
                throw $_.exception.message
            }
        }

        # Determine DAG membership
        $isDAGMember = $false
        try {
            $RecipientServer = $null; $RecipientServer = Get-MailboxServer -identity $Exchangeserver.fqdn -erroraction stop
            if ($($RecipientServer | measure).count -ne 1) {
                throw "$($($RecipientServer | measure).count) servers returned from query. Unable to continue."
            }
            if ($RecipientServer.DatabaseAvailabilityGroup -ne $null) {
                $isDAGMember = $true
            }
        } catch {
            throw $_.exception.message
        } 

        # Draining queues
        Write-Host "Putting '$($ExchangeServer.fqdn.toupper())' into maintenance mode."
        if ($RedirectionServer){
            Write-Host "Using '$($RedirectionServer.fqdn.toupper())' for message redirection."
        }
        Write-Host "Draining mail queues."
        try {
            Set-ServerComponentState -Identity $($ExchangeServer.fqdn) -Component HubTransport -State Draining -Requester Maintenance -erroraction stop
        } catch {
            throw $_.exception.message
        }

        # Restarting transport services
        Write-Host "Restarting MSExchangeTransport and MSExchangeFrontEndTransport services."
        $n = 0
        Do {
            try {
                invoke-command -ComputerName $($ExchangeServer.fqdn) -scriptblock {"MSExchangeTransport","MSExchangeFrontEndTransport" | restart-service -WarningAction SilentlyContinue} -ErrorAction stop -WarningAction SilentlyContinue
                break
            } catch {
                $n++
                write-host "WARNING: Issue restarting MSExchangeTransport and MSExchangeFrontEndTransport services. Waiting 60 seconds then retrying." -nonewline -ForegroundColor Yellow
                start-sleep -Seconds 60
                write-host " Retry attempt $n of 3." -ForegroundColor Yellow      
            }
            if ($n -eq 3) {
                write-warning "Issue restarting MSExchangeTransport and MSExchangeFrontEndTransport services. Continuing."
                break
            }
        } while ($true)

        # Redirect messages
        if ($RedirectionServer) {
            Write-Host "Redirecting messages."      
            try {
                Redirect-Message -Server $($ExchangeServer.fqdn) -Target $($RedirectionServer.fqdn) -confirm:$false -erroraction stop -WarningAction SilentlyContinue
            } catch {
                throw $_.exception.message
            }
        }

        # DAG members only
        if ($isDAGMember) {

            # Move active database copies off
            try {
                Write-Host "Setting DatabaseCopyActivationDisabledAndMoveNow to 'True'."
                Set-MailboxServer -Identity $($ExchangeServer.fqdn) -DatabaseCopyActivationDisabledAndMoveNow $True -erroraction Stop -confirm:$false
            } catch {
                throw $_.exception.message
            }

            # Move active copies immediately
            try {
                $actives = $null; $actives = Get-MailboxDatabaseCopyStatus *\$($ExchangeServer.name) | ? {$_.activecopy -eq $true}
                write-host "$($($actives | measure).count) active database copies found."

                if ($($($actives | measure).count) -eq 0 -and $MoveActiveDatabaseCopies) {
                    Write-host "No active database copies to move."
                }

                if ($actives -and $MoveActiveDatabaseCopies) {
                    write-host "Moving active databases to other DAG members."
                    $actives | . {
                        process {
                            if ($($($($_ | . { process {(get-Mailboxdatabase $_.databasename).servers}}) | measure).count) -lt 2) {
                                Write-Warning "No other database copies exist. Unable to move active database copy."
                            } else {
                                $move = $null;
                                try {
                                    $move = Get-Mailboxdatabase $($_.databasename) |  Move-ActiveMailboxDatabase -MountDialOverride lossless -SkipClientExperienceChecks -SkipMaximumActiveDatabasesChecks -confirm:$false -erroraction stop
                                    if ($move.status -ne "Succeeded") {
                                        throw "$($move.identity) Issue moving active database copy."
                                    }
                                } catch {
                                    write-warning $_.exception.message
                                }
                            }
                        }                        
                    }
                }

            } catch {
                throw $_.exception.message
            }

            # Suspend cluster node
            Write-Host "Suspending cluster node."      
            try {
                invoke-command -ComputerName $($ExchangeServer.fqdn) -ScriptBlock {
                    if ((Get-ClusterNode $($using:ExchangeServer.fqdn)).state -ne "Paused") {
                        Suspend-ClusterNode $($using:ExchangeServer.fqdn)
                    }     
                } -ErrorAction Stop | out-null
            } catch {
                throw $_.exception.message
            }

            # Set activation policy to blocked
            try {
                Write-Host "Setting DatabaseCopyAutoActivationPolicy to 'Blocked'."
                Set-MailboxServer -Identity $($ExchangeServer.fqdn) -DatabaseCopyAutoActivationPolicy Blocked -erroraction Stop -confirm:$false
            } catch {
                throw $_.exception.message
            }

            # Suspend passive copies
            try {                
                $Copies = $null; $Copies = Get-MailboxDatabaseCopyStatus *\$($ExchangeServer.name) | ? {$_.activecopy -eq $false}
                if ($Copies) {
                    Write-Host "Suspending passive copies."                
                    $Copies | . { process {
                            $_  | Suspend-MailboxDatabaseCopy -confirm:$false -erroraction stop
                        }                
                    }
                }
            } catch {
                throw $_.exception.message
            }

        }

        # Complete maintenance mode
        try {
            Write-Host "Completing maintenance mode."
            Set-ServerComponentState -Identity $($ExchangeServer.fqdn) -Component ServerWideOffline -State Inactive -Requester Maintenance -erroraction stop
        } catch {
            throw $_.exception.message
        }
        
        write-host "Done."     
        
    }
}

function Disable-EPMaintenanceMode {
    <#
    .SYNOPSIS
        Removes a Microsoft Exchange Server 2016 computer from maintenance mode.
  
    .DESCRIPTION
        Removes a Microsoft Exchange Server 2016 computer from maintenance mode. Cmdlet will -
  
            - set all server component states to active
            - resume the cluster node
            - enable database activation on the server
            - resume passive database copies
            - resume transport
            - restart transport services
  
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
  
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity
    )
    Process {        

        # Validate identity
        if ($input) {            
            $ExchangeServer = $null; $ExchangeServer = $input | Get-EPExchangeServer
        } else {
            $ExchangeServer = $null; $ExchangeServer = Get-EPExchangeServer -Identity $Identity
        }

        # Determine DAG membership
        $isDAGMember = $false
        try {
            $RecipientServer = $null; $RecipientServer = Get-MailboxServer -identity $Exchangeserver.fqdn -erroraction stop
            if ($($RecipientServer | measure).count -ne 1) {
                throw "$($($RecipientServer | measure).count) servers returned from query. Unable to continue."
            }
            if ($null -ne $RecipientServer.DatabaseAvailabilityGroup) {
                $isDAGMember = $true
            }
        } catch {
            throw $_.exception.message
        } 

        # Remove from maintenance mode
        try {
            Write-Host "Removing '$($ExchangeServer.fqdn.toupper())' from maintenance mode."
            Set-ServerComponentState -Identity $($ExchangeServer.fqdn) -Component ServerWideOffline -State Active -Requester Maintenance -erroraction stop
        } catch {
            throw $_.exception.message
        } 
        
        # DAG members only
        if ($isDAGMember) {
            
            # Resume cluster node
            Write-Host "Resuming cluster node."       
            try {
                invoke-command -ComputerName $($ExchangeServer.fqdn) -ScriptBlock {
                    if ((Get-ClusterNode $($using:ExchangeServer.fqdn)).state -ne "Up") {
                        Resume-ClusterNode $($using:ExchangeServer.fqdn)
                    }     
                } -ErrorAction Stop | out-null
            } catch {
                throw $_.exception.message
            }

            # Move active database copies on
            try {
                Write-Host "Setting DatabaseCopyActivationDisabledAndMoveNow to 'False'."
                Set-MailboxServer -Identity $($ExchangeServer.fqdn) -DatabaseCopyActivationDisabledAndMoveNow $false -erroraction Stop -confirm:$false
            } catch {
                throw $_.exception.message
            }     

            # Set activation policy to unrestricted
            try {
                Write-Host "Setting DatabaseCopyAutoActivationPolicy to 'Unrestricted'."
                Set-MailboxServer -Identity $($ExchangeServer.fqdn) -DatabaseCopyAutoActivationPolicy Unrestricted -erroraction Stop -confirm:$false
            } catch {
                throw $_.exception.message
            }   
            
            # Resume passive copies
            try {                
                $Copies = $null; $Copies = Get-MailboxDatabaseCopyStatus *\$($ExchangeServer.name) | ? {$_.activecopy -eq $false}
                if ($Copies) {
                    Write-Host "Resuming passive copies."
                    $Copies | . { process {
                            $_  | Resume-MailboxDatabaseCopy -confirm:$false -erroraction stop
                        }                
                    }
                }
            } catch {
                throw $_.exception.message
            }

        }     
        
        # Resume transport
        Write-Host "Resuming transport."
        try {
            Set-ServerComponentState -Identity $($ExchangeServer.fqdn) -Component HubTransport -State Active -Requester Maintenance -erroraction stop
        } catch {
            throw $_.exception.message
        }

        # Restarting transport services
        Write-Host "Restarting MSExchangeTransport and MSExchangeFrontEndTransport services."
        $n = 0
        Do {
            try {
                invoke-command -ComputerName $($ExchangeServer.fqdn) -scriptblock {"MSExchangeTransport","MSExchangeFrontEndTransport" | restart-service -WarningAction SilentlyContinue} -ErrorAction stop -WarningAction SilentlyContinue
                break
            } catch {
                $n++
                write-host "WARNING: Issue restarting MSExchangeTransport and MSExchangeFrontEndTransport services. Waiting 60 seconds then retrying." -nonewline -ForegroundColor Yellow
                Start-Sleep -Seconds 60
                write-host " Retry attempt $n of 3." -ForegroundColor Yellow      
            }
            if ($n -eq 3) {
                write-warning "Issue restarting MSExchangeTransport and MSExchangeFrontEndTransport services. Continuing."
                break
            }
        } while ($true)

        write-host "Done."

    }
}

function Get-EPAntimalwareStatus {
    <#
    .SYNOPSIS
        Gets the native antimalware status of an Exchange Server 2016 server.
 
    .DESCRIPTION
        Gets the native antimalware status of an Exchange Server 2016 server. Cmdlet searches the Windows Server Application logs for events and presents the results in an object oriented format.
 
    .PARAMETER Identity
        Specify the identity of the computer. This can be piped from Get-ExchangeServer or specified explicitly using a string.
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity
    )
    Process {      
        
        # Validate identity

        $ExchangeServer = $null
        try {
            if ($input) {            
                $ExchangeServer = $input | Get-EPExchangeServer
            } else {
                $ExchangeServer = Get-EPExchangeServer -Identity $Identity
            }
        } catch {
            throw $_.exception.message         
        }
  
        $Check = $null
        $CheckDateTime = $null
        $CheckInfo = $null
        try {
            $Check = Get-WinEvent -ComputerName $($ExchangeServer.fqdn) -FilterHashtable @{logname='application';ProviderName='Microsoft-Filtering-FIPFS';ID='6023','6024';Level='4'} -MaxEvents 1 -erroraction stop
            $CheckDateTime = $Check.TimeCreated
            $CheckInfo = $Check.message
        } catch {}


        $Update = $null
        $UpdateDateTime = $null
        $UpdateInfo = $null
        try {
            $Update = Get-WinEvent -ComputerName $($ExchangeServer.fqdn) -FilterHashtable @{logname='application';ProviderName='Microsoft-Filtering-FIPFS';ID='6033';Level='4'} -MaxEvents 1 -erroraction stop
            $UpdateDateTime = $Update.TimeCreated
            $UpdateInfo = $Update.message
        } catch {}

        $Problem = $null
        $ProblemDateTime = $null
        $ProblemInfo = $null
        try {
            $Problem = Get-WinEvent -ComputerName $($ExchangeServer.fqdn) -FilterHashtable @{logname='application';ProviderName='Microsoft-Filtering-FIPFS';Level='1','2','3'} -MaxEvents 1 -erroraction stop
            $ProblemDateTime = $Problem.TimeCreated
            $ProblemInfo = $Problem.message
        } catch {}

        try {
            [pscustomobject]@{
                "Identity" = $($ExchangeServer.fqdn)
                "CheckInfo" = $CheckInfo
                "UpdateInfo" = $UpdateInfo
                "ErrorInfo" = $ProblemInfo
                "WhenChecked" = $CheckDateTime
                "WhenUpdated" = $UpdateDateTime
                "WhenError" = $ProblemDateTime
            }
        } catch {
            throw $_.exception.message
        }

    }
}


# Mail enabled objects cmdlets and functions

function Remove-EPProxyAddress{
    <#
    .SYNOPSIS
        Removes secondary SMTP addresses from mail enabled objects that match a specific domain.
 
    .DESCRIPTION
        Removes secondary SMTP addresses from mail enabled objects that match a specific domain.
 
    .PARAMETER Identity
        Specify the identity of the mail enabled object. This can be piped from Get-Recipient, Get-Recipient, Get-DistributionGroup etc or specified explicitly using a string.
 
    .PARAMETER SMTPDomain
        Specify the SMTP domain that you wish to have removed from the object's proxy addresses.
     
    .PARAMETER X500Keyword
        Specify a keyword that can be matched to an X500 address that you wish to have removed from the object's proxy addresses.
 
    .PARAMETER Confirm
        Specify if you want to be prompted. The default is true.
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][string]$SMTPDomain,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][string]$X500Keyword,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][Boolean]$Confirm=$true
    )

    Process {

        $Pxys = $null
        $Recipient = $null
        $Status = $null
        $Comment = $null
        $SMTPDomain = $SMTPDomain.toupper()

        $MailObj = [pscustomobject]@{
            "Identity" = $null
            "GUID" = $null
            "RecipientTypeDetails" = $null
            "Status" = $Status
            "Comment" = $Comment
        }

        try {
            if ($input) {
                $Recipient = $Input
                if (!($Recipient.recipienttypedetails)) {
                    $MailObj.identity = $Input.identity
                    throw "Issue with input object."
                }
            }

            if (!($input)) {
                $Recipient = Get-Recipient -identity $Identity -erroraction stop                
            }

            if (!($Recipient)) {
                throw "Recipient not found."
            }

            if (($Recipient | measure).count -gt 1) {
                throw "Too many matches found."
            }

            $MailObj.identity = $Recipient.identity
            $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
            $MailObj.GUID = $Recipient.guid.guid

            if ($Recipient.exchangeversion.exchangebuild.major -ne 15) {
                write-warning "Exchange version is not 15 for '$($Recipient.identity)'. There may be issues."
                $Comment += "Exchange version is not 15. There may be issues."
            }

            $Pxys = ($Recipient).emailaddresses.proxyaddressstring | sort 

            if (!($Pxys)) {
                throw "No proxy addresses found."
            }

            $PxysToRemove = $null

            if (!($SMTPDomain -or $X500Keyword)) {
                throw "No parameters passed to cmdlet."
            }

            if ($SMTPDomain) {
                $PxysToRemove = $Pxys | sort | ? {($_ -match "$SMTPDomain$" -and $_ -cmatch "^smtp:")}
                $Pxys = $Pxys | sort | ? {!($_ -match "$SMTPDomain$" -and $_ -cmatch "^smtp:")}           
            }

            if ($X500Keyword) {
                $PxysToRemove += $Pxys | ? {($_ -match "^X500:" -and $_ -match $X500Keyword)}
                $Pxys = $Pxys | sort | ? {!($_ -match "^X500:" -and $_ -match $X500Keyword)} 
            }


            if (!($PxysToRemove)) {
                $MailObj.Status = "OK"
            } else {
                $ADObj = $null
                $GUID = $null
                $GUID = $Recipient.guid.guid
                $ADObj = Get-ADObject -Filter {objectguid -eq $GUID} -Properties proxyaddresses -Server $recipient.originatingserver
                if (!($ADObj)) {
                    throw "Recipient not found in Active Directory."
                }

                $Pxys = $Pxys | . { process{ $_.tostring()}}
                $ADObj.proxyaddresses = $Pxys
                
                if ($Confirm) {
                    write-host "Are you sure you want to remove proxy addresses from '$($Recipient.identity)'?"
                    write-host ""
                    write-host "Proxy addresses to keep -`n"
                    $Pxys
                    write-host ""
                    Write-host "Proxy addresses to remove -`n"
                    $PxysToRemove
                    write-host ""
                    write-host "[Y] Yes " -ForegroundColor Yellow -NoNewline
                    write-host '[N] No (default is "Y"): ' -NoNewline                    
                    $Read = Read-Host
                }
                if (!($Read)) {
                    $Read = "Y"
                }
                if ($Read -match "^Y$|^Yes$") {
                    Set-ADObject -Instance $ADObj -Server $recipient.originatingserver -erroraction stop
                } else {
                    throw "Cancelled by user."
                }

                $MailObj.status = "Updated"
                $MailObj.Comment += "Removed $($PxysToRemove -join ";")"
            }

        } catch {
            $MailObj.Status = "Error"
            $MailObj.Comment += $_.exception.message
        }
   
        $MailObj

    }
}

function ConvertTo-EPMailUser{
    <#
    .SYNOPSIS
        Converts a mailbox to a mail user.
 
    .DESCRIPTION
        Converts a mailbox to a mail user.
 
    .PARAMETER Identity
        Specify the identity of the mailbox enabled object. This can be piped from Get-Recipient, Get-Mailbox etc or specified explicitly using a string.
 
    .PARAMETER ExternalEmailAddress
        Specify the ExternalEmailAddress of the mail user. If this is not specified the primary SMTP address will be used.
     
    .PARAMETER Confirm
        Specify if you want to be prompted. The default is true.
 
    #>
    
    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$false)][string]$ExternalEmailAddress,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][Boolean]$Confirm=$true
    )

    Process {

        $MailObj = [pscustomobject]@{
            "Identity" = $null
            "GUID" = $null
            "RecipientTypeDetails" = $null
            "ExternalEmailAddress" = $null
            "Status" = $Status
            "Comment" = $Comment
        }

        try {

            $Recipient = $null

            if ($input) {
                $Recipient = $Input
                if (!($Recipient.recipienttypedetails)) {
                    $MailObj.identity = $Input.identity
                    throw "Issue with input object."
                } else {
                    if (!($Recipient.recipienttypedetails -match "mailbox$" -or $Recipient.recipienttypedetails -match "mailuser$")) {
                        $MailObj.identity = $Input.identity
                        throw "Issue with input object."
                    }
                }
            }

            if (!($input)) {
                $Recipient = Get-Recipient -identity $Identity -erroraction stop                
            }

            if (!($Recipient)) {
                throw "Recipient not found."
            }

            if (($Recipient | measure).count -gt 1) {
                throw "Too many matches found."
            }

            if ($Recipient.exchangeversion.exchangebuild.major -ne 15) {
                write-warning "Exchange version is not 15 for '$($Recipient.identity)'. There may be issues."
                $Comment += "Exchange version is not 15. There may be issues."
            }

            $MailObj.identity = $Recipient.identity
            $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
            $MailObj.GUID = $Recipient.guid.guid


            if ($ExternalEmailAddress) {               
                $MailObj.ExternalEmailAddress = $ExternalEmailAddress
            } else {
                $MailObj.ExternalEmailAddress = $Recipient.primarysmtpaddress
            }
            
            $TargetAddress = $null
            $TargetAddress = $MailObj.ExternalEmailAddress
            if ($TargetAddress -notmatch "^smtp:") {
                $TargetAddress = "SMTP:" + $TargetAddress
            }

            if ($Recipient.recipienttypedetails -eq "mailuser" -and $Recipient.ExternalEmailAddress -ceq $TargetAddress) {

                $MailObj.Status = "OK"

            } else {

                $ADObj = $null
                $ADObj = Get-ADObject -Identity $MailObj.GUID -Properties homeMDB,msExchHomeServerName,msExchMailboxGUID,msExchArchiveGUID,msExchArchiveName,msExchRecipientDisplayType,msExchRecipientTypeDetails,targetaddress -Server $recipient.originatingserver
                $ADObj.homeMDB = $null
                $ADObj.msExchHomeServerName = $null
                $ADObj.msExchMailboxGUID = $null
                $ADObj.msExchArchiveGUID = $null
                $ADObj.msExchArchiveName = $null
                $ADObj.msExchRecipientDisplayType = 6
                $ADObj.msExchRecipientTypeDetails = 128
                $ADObj.targetAddress = $TargetAddress

                if ($Confirm) {
                    write-host "Are you sure you want to convert the mailbox to a mailuser using ExternalEmailAddress '$TargetAddress' for '$($Recipient.identity)'?"
                    write-host "[Y] Yes " -ForegroundColor Yellow -NoNewline
                    write-host '[N] No (default is "Y"): ' -NoNewline                    
                    $Read = Read-Host
                }
                if (!($Read)) {
                    $Read = "Y"
                }
                if ($Read -match "^Y$|^Yes$") {
                    Set-ADObject -Instance $ADObj -Server $recipient.originatingserver -erroraction stop
                } else {
                    throw "Cancelled by user."
                }

                $MailObj.Status = "Updated"
                $MailObj.Comment += "ExternalEmailAddress set to '$TargetAddress'"
            }

        } catch {
            $MailObj.Status = "Error"
            $MailObj.Comment += $_.exception.message
        }

        $MailObj

    }
}

function ConvertTo-EPMailContact{
    <#
    .SYNOPSIS
        Converts a mailbox or mail user to a mail contact.
 
    .DESCRIPTION
        Converts a mailbox or mail user to a mail contact. The user object will have Exchange attributes removed and a mail contact object will be created in the same organizational unit unless specified with the OrganizationalUnit parameter.
 
    .PARAMETER Identity
        Specify the identity of the mailbox or mail enabled object. This can be piped from Get-Recipient, Get-Mailbox etc or specified explicitly using a string.
 
    .PARAMETER ExternalEmailAddress
        Specify the ExternalEmailAddress of the mail contact. If this is not specified for a mailbox the primary SMTP address will be used.
        If this is not specified for a mail user to ExternalEmailAddress of the mail user will be used.
 
    .PARAMETER OrganizationalUnit
        Specify where you would like the mail contact to be created. If not specified the same organizationalunit as the user object will be used.
 
    .PARAMETER Confirm
        Specify if you want to be prompted. The default is true.
 
    #>
    
    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$false)][string]$ExternalEmailAddress,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$false)][string]$OrganizationalUnit,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][Boolean]$Confirm=$true
    )

    Process {

        $MailObj = [pscustomobject]@{
            "Identity" = $null
            "GUID" = $null
            "RecipientTypeDetails" = $null
            "ExternalEmailAddress" = $null
            "Status" = $Status
            "Comment" = $Comment
        }

        try {

            $Recipient = $null

            if ($input) {
                $Recipient = $Input
                if (!($Recipient.recipienttypedetails)) {
                    $MailObj.identity = $Input.identity
                    throw "Issue with input object."
                } else {
                    if (!($Recipient.recipienttypedetails -match "mailbox$" -or $Recipient.recipienttypedetails -match "mailuser$" -or $Recipient.recipienttypedetails -match "mailcontact$")) {
                        $MailObj.identity = $Input.identity
                        throw "Issue with input object."
                    }
                }
            }

            if (!($input)) {
                $Recipient = Get-Recipient -identity $Identity -erroraction stop                
            }

            if (!($Recipient)) {
                throw "Recipient not found."
            }

            if (($Recipient | measure).count -gt 1) {
                throw "Too many matches found."
            }

            if ($Recipient.exchangeversion.exchangebuild.major -ne 15) {
                write-warning "Exchange version is not 15 for '$($Recipient.identity)'. There may be issues."
                $Comment += "Exchange version is not 15. There may be issues."
            }

            $MailObj.identity = $Recipient.identity
            $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
            $MailObj.GUID = $Recipient.guid.guid

            if ($ExternalEmailAddress) {
                $MailObj.ExternalEmailAddress = $ExternalEmailAddress
            } else {
                if ($Recipient.recipienttypedetails -match "mailbox$") {
                    $MailObj.ExternalEmailAddress = $Recipient.primarysmtpaddress.address
                }
                if ($Recipient.recipienttypedetails -match "mailuser$") {
                    if ($Recipient.ExternalEmailAddress) {
                        $MailObj.ExternalEmailAddress = $Recipient.ExternalEmailAddress
                    }
                }
            }

            $TargetAddress = $null
            $TargetAddress = $MailObj.ExternalEmailAddress
            if ($TargetAddress -notmatch "^smtp:") {
                $TargetAddress = "SMTP:" + $TargetAddress
            }

            if ($Recipient.recipienttypedetails -eq "mailcontact") {

                $MailObj.Status = "Error"
                $MailObj.Comment += "MailContact objects not supported."

            } else {

                if ($Confirm) {
                    write-host "Are you sure you want to convert to a mail contact using ExternalEmailAddress '$TargetAddress' for '$($Recipient.identity)'?"
                    write-host "[Y] Yes " -ForegroundColor Yellow -NoNewline
                    write-host '[N] No (default is "Y"): ' -NoNewline                    
                    $Read = Read-Host
                }
                if (!($Read)) {
                    $Read = "Y"
                }
                if ($Read -match "^Y$|^Yes$") {    
        
                    if (!($Recipient.primarysmtpaddress.address)) {
                        throw "Missing primary SMTP address."
                    }

                    $TempSMTPAddress = $null
                    $TempSMTPAddress = [guid]::NewGuid().guid + "@tempaddr.local"

                    $Pxys = $null; $Pxys = @()
                    $Pxys += $Recipient.emailaddresses.proxyaddressstring

                    $X500 = (get-adobject -Identity $recipient.guid.guid -Properties legacyexchangedn -Server $recipient.originatingserver).legacyexchangedn
                    
                    if (!($X500)) {
                        throw "LegacyExchangeDN is null."
                    }

                    $X500 = "X500:" + $X500
                    $Pxys += $X500
                    $Pxys = $Pxys | . {process{$_.tostring()}}

                    $ContactName = $null
                    $ContactName = $Recipient.name + "-MailContact"
                    $ConObj = $null

                    if (!($OrganizationalUnit)) {
                        $ConObj = New-MailContact -Name $ContactName -Displayname $($Recipient.Displayname) -OrganizationalUnit $($Recipient.OrganizationalUnit) -PrimarySMTPAddress $TempSMTPAddress -ExternalEmailAddress $TargetAddress -erroraction stop
                    } else {
                        $ConObj = New-MailContact -Name $ContactName -Displayname $($Recipient.Displayname) -OrganizationalUnit "$OrganizationalUnit" -PrimarySMTPAddress $TempSMTPAddress -ExternalEmailAddress $TargetAddress -erroraction stop
                    }

                    if (!($ConObj)) {
                         throw "Issue creating mail contact."
                    } else {
                        if ($ConObj.EmailAddressPolicyEnabled) {
                            Set-MailContact -Identity $ConObj.guid.guid -EmailAddressPolicyEnabled $false -domaincontroller $recipient.originatingserver -erroraction stop
                        }
                    }

                    switch -regex ($Recipient.recipienttypedetails) {
                        'mailbox$'      {
                                            Disable-Mailbox -Identity $Recipient.guid.guid -confirm:$false -erroraction stop
                                            Set-ADObject -Identity $recipient.guid.guid -clear legacyexchangedn -Server $recipient.originatingserver -erroraction stop
                                        }
                        'mailuser$'     {
                                            Disable-MailUser -Identity $Recipient.guid.guid -confirm:$false -erroraction stop    
                                            Set-ADObject -Identity $recipient.guid.guid -clear legacyexchangedn -Server $recipient.originatingserver -erroraction stop                                      
                                        }
                        default { throw "Unsupported '$($Recipient.recipienttypedetails)'"}
                    }
                    
                    Set-MailContact -identity $ConObj.guid.guid -EmailAddresses $Pxys -domaincontroller $recipient.originatingserver -erroraction stop                

                } else {
                    throw "Cancelled by user."
                }

                $MailObj.Status = "Updated"
                $MailObj.Comment += "Created '$ContactName'. ExternalEmailAddress set to '$TargetAddress'"
            }

        } catch {
            $MailObj.Status = "Error"
            $MailObj.Comment += $_.exception.message
        }

        $MailObj

    }
}

function Clear-EPAutoMapping{
    <#
    .SYNOPSIS
        Removes all automapped mailboxes.
 
    .DESCRIPTION
        Removes all automapped mailboxes. Please note this does not remove any mailbox permissions.
 
    .PARAMETER Identity
        Specify the identity of the mailbox or mail enabled object. This can be piped from Get-Recipient, Get-Mailbox etc or specified explicitly using a string.
 
    .PARAMETER Confirm
        Specify if you want to be prompted. The default is true.
 
    #>
    
    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$false,valuefrompipelinebypropertyname=$true)][Boolean]$Confirm=$true
    )

    Process {

        $MailObj = [pscustomobject]@{
            "Identity" = $null
            "GUID" = $null
            "RecipientTypeDetails" = $null
            "Status" = $Status
            "Comment" = $Comment
        }

        try {

            $Recipient = $null

            if ($input) {
                $Recipient = $Input
                if (!($Recipient.recipienttypedetails)) {
                    $MailObj.identity = $Input.identity
                    throw "Issue with input object."
                } else {
                    if (!($Recipient.recipienttypedetails -match "mailbox$" -or $Recipient.recipienttypedetails -match "mailuser$")) {
                        $MailObj.identity = $Input.identity
                        $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
                        $MailObj.GUID = $Recipient.guid.guid
                        throw "Issue with input object."
                    }
                }
            }

            if (!($input)) {
                $Recipient = Get-Recipient -identity $Identity -erroraction stop                
            }

            if (!($Recipient)) {
                throw "Recipient not found."
            }

            if (($Recipient | measure).count -gt 1) {
                throw "Too many matches found."
            }

            if ($Recipient.exchangeversion.exchangebuild.major -ne 15) {
                write-warning "Exchange version is not 15 for '$($Recipient.identity)'. There may be issues."
                $Comment += "Exchange version is not 15. There may be issues."
            }

            $MailObj.identity = $Recipient.identity
            $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
            $MailObj.GUID = $Recipient.guid.guid

            $AutoBL = $null; $AutoBL = (Get-ADObject $($MailObj.GUID) -properties msExchDelegateListBL).msExchDelegateListBL

            if (!($AutoBL)) {
                $MailObj.Status = "OK"
                $MailObj.Comment += "No automapping found."
            } else {

                if ($Confirm) {
                    write-host "Are you sure you want to remove all automapping for '$($Recipient.identity)'?"
                    write-host ""
                    write-host "The following will be removed -"
                    write-host ""
                    $AutoBL
                    write-host ""
                    write-host "[Y] Yes " -ForegroundColor Yellow -NoNewline
                    write-host '[N] No (default is "Y"): ' -NoNewline            
                    $Read = Read-Host
                }
                if (!($Read)) {
                    $Read = "Y"
                }

                if ($Read -notmatch "^Y$|^Yes$") {
                    throw "Cancelled by user."
                }

                $AutoBL | . { process {
                    $ADObj = $null;
                    $DN = $null; $DN = $_
                    try {
                        $ADObj = Get-ADObject $DN -Properties msExchDelegateListLink -Server $recipient.originatingserver
                        $ADObj.msExchDelegateListLink = $ADObj.msExchDelegateListLink | . { process {if ($_ -ne $recipient.distinguishedname){$_}}} | . { process {$_.tostring()}}
                        Set-ADObject -Instance $ADObj -Server $recipient.originatingserver
                        $MailObj.Comment += "Removed: $DN`n"
                    } catch {
                        $MailObj.Comment += "Error: $DN $($_.exception.message)`n"
                    }
                }}
                if ($MailObj.comment -notmatch "Error\:") {
                    $MailObj.Status = "OK"
                } else {
                    if ($MailObj.comment -notmatch "Removed\:") {
                        $MailObj.Status = "Error"
                    } else {
                        $MailObj.Status = "Warn"
                    }
                }
            }

        } catch {
            $MailObj.Status = "Error"
            $MailObj.Comment += $_.exception.message
        }

        $MailObj

    }
}

function Convert-EPIMCEAEXtoX500{
    <#
    .SYNOPSIS
        Converts IMCEAEX to X500 format.
 
    .DESCRIPTION
        Converts IMCEAEX to X500 format which is a useable proxy address string for recipients. Note the following -
 
        - If a recipient was accidentally mail or mailbox disabled the legacyexchangedn property would be cleared on the recipient object.
        - If the recipient is mail enabled again, Exchange would generate a new legacyexchangedn.
        - This creates a problem for cached Outlook lookups that used the old legacyexchangedn value.
        - Exchange will generate an undeliverable report if a stale cached lookup is used and presents the address in IMCEAEX format. E.g. IMCEAEX-_o=Example+20Org_ou=First+20Administrative+20Group_cn=Recipients_cn=Example+2ERecipient@domain.com
        - You can convert the IMCEAEX to X500 format and add it to the recipients emailaddresses property. Cached Outlook lookups will work again.
 
    .PARAMETER IMCEAEX
        Specify the IMCEAEX address as a string.
 
    #>
    
    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true)][string]$IMCEAEX
    )

    Process {
        try {
            $X500 = $null; $X500 = $IMCEAEX.replace("+20", " ").replace("+28", "(").Replace("+29", ")").replace("IMCEAEX-", "X500:").replace("_", "/").replace("+2E", ".").replace("+2C", ",").split("@")[0]
        } catch {
            throw $_.exception.message
        }
        return $X500
    }
}

function Import-EPPSTs {
    <#
    .SYNOPSIS
        Bulk import multiple PST files.
 
    .DESCRIPTION
        Used to import multiple PST files from a directory into a mailbox or online archive mailbox.
 
    .PARAMETER Identity
        Specify the identity of the mailbox. This can be piped from Get-ExchangeServer or specified explicitly using a string.
     
    .PARAMETER Path
        Specify the unc path to the PST files. Cmdlet will recursively locate PST files to import. The Exchange Trusted Subsystem must have permissions.
 
    .PARAMETER ToArchiveMailbox
        Specify whether to import PST files to an online archive mailbox. This is enabled by default.
 
    .PARAMETER Confirm
        Specify whether a confirmation is required before importing. Default is True.
         
    .EXAMPLE
        Import-EPPSTs -Identity User01 -Path C:\PSTs -ToArchiveMailbox $false
 
        The above command will import the PSTs found in C:\PSTs into the primary mailbox for the identity User01.
 
    #>

    [cmdletbinding()]
    Param (
        [Parameter(mandatory=$true,valuefrompipelinebypropertyname=$true)][PSCustomObject]$Identity,
        [Parameter(mandatory=$true)][String]$Path,
        [Parameter(mandatory=$false)][Boolean]$ImportToArchive=$true,
        [Parameter(mandatory=$false)][Boolean]$Confirm=$true
    )

    Process {

        $MailObj = [pscustomobject]@{
            "Identity" = $null
            "GUID" = $null
            "RecipientTypeDetails" = $null
            "Path" = $Path
            "ImportToArchive" = $ImportToArchive
            "PSTs" = @()
            "TotalSize(MB)" = $null
            "Commands" = @()
            "Status" = $Status
            "Comment" = $Comment
        }

        try {

            $Recipient = $null
            $timestamp = ("{0:yyyyMMddHHmmss}" -f (get-date)).tostring()

            if ($input) {
                $Recipient = $Input
                if (!($Recipient.recipienttypedetails)) {
                    $MailObj.identity = $Input.identity
                    throw "Issue with input object."
                } else {
                    if (!($Recipient.recipienttypedetails -match "mailbox$" -or $Recipient.recipienttypedetails -match "mailuser$")) {
                        $MailObj.identity = $Input.identity
                        $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
                        $MailObj.GUID = $Recipient.guid.guid
                        throw "Issue with input object."
                    }
                }
            }

            if (!($input)) {
                $Recipient = Get-Recipient -identity $Identity -erroraction stop                
            }

            if (!($Recipient)) {
                throw "Recipient not found."
            }

            if (($Recipient | measure).count -gt 1) {
                throw "Too many matches found."
            }

            if ($Recipient.exchangeversion.exchangebuild.major -ne 15) {
                write-warning "Exchange version is not 15 for '$($Recipient.identity)'. There may be issues."
                $Comment += "Exchange version is not 15. There may be issues."
            }

            $MailObj.identity = $Recipient.identity
            $MailObj.RecipientTypeDetails = $Recipient.RecipientTypeDetails
            $MailObj.GUID = $Recipient.guid.guid

            $dbname = $null;
            if ($importtoarchive) {
                $dbname = $recipient.archivedatabase.name
            } else {
                $dbname = $recipient.database.name
            }

            if (!($dbname)) {
                if ($importtoarchive) {
                    throw "No archive database has been identified for this recipient."
                } else {
                    throw "No database has been identified for this recipient."
                }
            }

            if ($dbname) {
                $circ = $null; $circ = (Get-MailboxDatabase $($dbname)).circularloggingenabled
                if (!($circ)){
                    write-warning "Circular logging is not enabled for database '$($dbname)'. If you have a large amount of mail data to import this may result in significant transaction log growth for this database."
                    $MailObj.Comment += "Circular logging is not enabled for database '$($dbname)'. "
                }
            }

            if (!(test-path $Path)) {
                $Comment += "Issue with path."
                throw "Issue with path."
            } else {
                if ($Path -notmatch "^\\\\") {
                    $Comment += "Path is not a UNC path."
                    throw "Path is not a UNC path."
                }
            }

            $PSTs = $null; $PSTs = gci $Path *.pst -recurse
            $PSTs | % {$MailObj.PSTs += $_.versioninfo.filename}
            $MailObj."totalsize(mb)" = ($PSTs | measure length -sum ).sum / 1000000

            if ($MailObj.PSTs) {
                $n = 0
                $MailObj.PSTs | . {process {
                    $PST = $null; $PST = $_
                    $thiscmd = $null; $thiscmd = "new-mailboximportrequest -BadItemLimit 1000 -AcceptLargeDataLoss -name ""$($mailobj.guid)`-$timestamp`-$n"" -mailbox $($mailobj.guid) -filepath $_ -erroraction stop"
                    if ($importtoarchive) {
                        $thiscmd += " -isarchive"
                    }
                    $MailObj.Commands += $thiscmd
                }}
            }

            if (!($MailObj.Commands)) {
                throw "No PSTs found to import."
            }

            if ($Confirm) {
                if ($importtoarchive) {
                    write-host "Are you sure you want to import $($MailObj."totalsize(mb)") MB of PST mail data into the archive mailbox for '$($Recipient.identity)'?"
                } else {
                    write-host "Are you sure you want to import $($MailObj."totalsize(mb)") MB of PST mail data into the primary mailbox for '$($Recipient.identity)'?"
                }
                write-host "[Y] Yes " -ForegroundColor Yellow -NoNewline
                write-host '[N] No (default is "Y"): ' -NoNewline                    
                $Read = Read-Host
            }
            if (!($Read)) {
                $Read = "Y"
            }
            if ($Read -match "^Y$|^Yes$") {
                
            } else {
                throw "Cancelled by user."
            }
            
            if ($MailObj.Commands) {
                $MailObj.Commands | . { process {
                    $thiscmd = $null; $thiscmd = $_
                    try {                        
                        invoke-expression "[void]($_)" -erroraction stop
                    } catch {
                        $MailObj.comment += "Issue invoking '$thiscmd'."
                        $MailObj.status = "Warning"
                        $_                        
                    }
                }}
            }

        } catch {
            $MailObj.Status = "Error"
            $MailObj.Comment += $_.exception.message
        }

        if (!($MailObj.status)) {
            $MailObj.status = "OK"
        }

        $MailObj

    }
}



Function Compare-ObjectProperties {
    Param(
        [PSObject]$ReferenceObject,
        [PSObject]$DifferenceObject  
    )
    $objprops = $ReferenceObject | Get-Member -MemberType Property,NoteProperty | % Name
    $objprops += $DifferenceObject | Get-Member -MemberType Property,NoteProperty | % Name
    $objprops = $objprops | Sort | Select -Unique
    $diffs = @()
    foreach ($objprop in $objprops) {
        $diff = Compare-Object $ReferenceObject $DifferenceObject -Property $objprop
        if ($diff) {            
            $diffprops = @{
                PropertyName=$objprop
                RefValue=($diff | ? {$_.SideIndicator -eq '<='} | % $($objprop))
                DiffValue=($diff | ? {$_.SideIndicator -eq '=>'} | % $($objprop))
            }
            $diffs += New-Object PSObject -Property $diffprops
        }        
    }
    if ($diffs) {return ($diffs | Select PropertyName,RefValue,DiffValue)}     
}