ADSyncConfig.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
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
<#
  
.SYNOPSIS
    Prepares Active Directory configuration for various purposes.
 
.DESCRIPTION
 
    AdSyncConfig.psm1 is a Windows PowerShell script module that provides functions that are
    used to prepare your Active Directory forest and domains for Azure AD Connect Sync
    features.
#>


#----------------------------------------------------------
# STATIC VARIABLES
#----------------------------------------------------------
# Well known SIDS
$selfSid = "S-1-5-10"
$enterpriseDomainControllersSid = "S-1-5-9"

# Regex variables
$distinguishedNameRegex = [Regex] '^(?:(?<cn>CN=(?<name>[^,]*)),)?(?:(?<path>(?:(?:CN|OU)=[^,]+,?)+),)?(?<domain>(?:DC=[^,]+,?)+)$'
$defaultADobjProperties = @('UserPrincipalName','ObjectGUID','ObjectSID','mS-DS-ConsistencyGuid','sAMAccountName','objectSid')

# Parameter variables
$commaSeparator =","
$periodSeparator = "."
$colonSeparator = ":"
$atSeparator = "@"
$aclSeparator = '" "'
$inheritanceSubObjectsOnly = 'S'
$inheritanceThisAndSubObjects = 'T'
$inheritanceNone = 'N'

<#
    .SYNOPSIS
        Tighten permissions on an AD object that is not otherwise included in any AD protected security group.
        A typical example is the AD Connect account (MSOL) created by AAD Connect automatically. This account
        has replicate permissions on all domains, however can be easily compromised as it is not protected.
 
    .DESCRIPTION
        The Set-ADSyncRestrictedPermissions Function will tighten permissions oo the
        account provided. Tightening permissions involves the following steps:
        1. Disable inheritance on the specified object
        2. Remove all ACEs on the specific object, except ACEs specific to SELF. We want to keep
           the default permissions intact when it comes to SELF.
        3. Assign these specific permissions:
 
                Type Name Access Applies To
                =============================================================================================
                Allow SYSTEM Full Control This object
                Allow Enterprise Admins Full Control This object
                Allow Domain Admins Full Control This object
                Allow Administrators Full Control This object
 
                Allow Enterprise Domain Controllers List Contents
                                                                    Read All Properties
                                                                    Read Permissions This object
 
                Allow Authenticated Users List Contents
                                                                    Read All Properties
                                                                    Read Permissions This object
 
    .PARAMETER ADConnectorAccountDN
        DistinguishedName of the Active Directory account whose permissions need to be tightened. This is typically the MSOL_nnnnnnnnnn
        account or a custom domain account that is configured in your AD Connector.
 
    .PARAMETER Credential
        Administrator credential that has the necessary privileges to restrict the permissions on the ADConnectorAccountDN account.
        This is typically the Enterprise or Domain administrator.
        Use the fully qualified domain name of the administrator account to avoid account lookup failures. Example: CONTOSO\admin
 
    .PARAMETER DisableCredentialValidation
        When DisableCredentialValidation is used, the function will not check if the credentials provided in -Credential are valid in AD
        and if the account provided has the necessary privileges to restrict the permissions on the ADConnectorAccountDN account.
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .EXAMPLE
       Set-ADSyncRestrictedPermissions -ADConnectorAccountDN "CN=TestAccount1,CN=Users,DC=Contoso,DC=com" -Credential $(Get-Credential)
#>

Function Set-ADSyncRestrictedPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param(
        [Parameter(Mandatory=$True)] 
        [string] $ADConnectorAccountDN,

        [Parameter(Mandatory=$True)] 
        [System.Management.Automation.PSCredential] $Credential,

        [Parameter(Mandatory=$False)] 
        [switch] $DisableCredentialValidation,

        [string] $TargetForest = $null
    )

    # Function init
    [string] $functionMsg = "Set-ADSyncRestrictedPermissions:"

    If (!$DisableCredentialValidation)
    {
        # Validate Credential
        TestCredential $Credential
    }

    If ($PSCmdlet.ShouldProcess($ADConnectorAccountDN, "Set restricted permissions")) 
    {
        $networkCredential = $Credential.GetNetworkCredential()
        If ($TargetForest)
        {
            $path = "LDAP://" + $TargetForest + "/" + $ADConnectorAccountDN    
        }
        Else
        {
            $path = "LDAP://" + $networkCredential.Domain + "/" + $ADConnectorAccountDN        
        }
        
        $de = New-Object System.DirectoryServices.DirectoryEntry($path, $Credential.UserName, $networkCredential.Password)
        $selfName = ConvertSIDtoName $selfSid            

        Try
        {    
            [System.DirectoryServices.DirectoryEntryConfiguration]$deOptions = $de.get_Options()
            $deOptions.SecurityMasks = [System.DirectoryServices.SecurityMasks]::Dacl
        }
        Catch
        {
            Throw "$functionMsg Failure using credential to access Active Directory. Error Details: $($_.Exception.Message)"
        }

        Try
        {
            Write-Output "$functionMsg Setting Restricted permissions on '$ADConnectorAccountDN'..."
            # disable inheritance on the object and remove inherited DACLs
            $de.ObjectSecurity.SetAccessRuleProtection($true, $false);

            # remove all DACLs on the object except SELF
            $acl = $de.ObjectSecurity.GetAccessRules($true, $false, [System.Security.Principal.NTAccount])
            ForEach ($ace in $acl) 
            {
                If ($ace.IdentityReference -ne $selfName) 
                {
                    $de.ObjectSecurity.RemoveAccessRule($ace) > $null
                }
            }

            # Add specific DACLs on the object
            # Add Full Control for SYSTEM
            $systemSid = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::LocalSystemSid, $null)
            $systemDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($systemSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericAll, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($systemDacl)

            # Add Full Control for Enterprise Admins
            $eaSid = GetEnterpriseAdminsSid $Credential
            $eaDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($eaSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericAll, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($eaDacl)

            # Add Full Control for Domain Admins
            $daSid = GetDomainAdminsSid $Credential
            $daDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($daSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericAll, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($daDacl)

            # Add Full Control for Administrators
            $adminSid = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid, $null)
            $adminDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($adminSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericAll, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($adminDacl)

            # Add Generic Read for ENTERPRISE DOMAIN CONTROLLERS
            $edcSid = New-Object System.Security.Principal.SecurityIdentifier($enterpriseDomainControllersSid)
            $edcDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($edcSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericRead, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($edcDacl)

            # Add Generic Read for Authenticated Users
            $authenticatedUsersSid = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::AuthenticatedUserSid, $null)
            $authenticatedUsersDacl = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($authenticatedUsersSid, [System.DirectoryServices.ActiveDirectoryRights]::GenericRead, [System.Security.AccessControl.AccessControlType]::Allow)
            $de.ObjectSecurity.AddAccessRule($authenticatedUsersDacl)

            $de.CommitChanges()
        }
        Catch [Exception]
        {
            Throw "$functionMsg Setting Restricted permissions on $ADConnectorAccountDN failed. Error Details: $($_.Exception.Message)"
        }
        Finally
        {
            If ($de -ne $null)
            {
                $de.Dispose()
            }            
        }
    }
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for password hash synchronization.
 
    .DESCRIPTION
        The Set-ADSyncPasswordHashSyncPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Replicating Directory Changes
        2. Replicating Directory Changes All
 
        These permissions are given to all domains in the forest.
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncPasswordHashSyncPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncPasswordHashSyncPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
#>

Function Set-ADSyncPasswordHashSyncPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls = "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes`"" + " " 
    $acls += "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes All`""

    # Set root permissions for all Domains in the Forest
    $message = "Grant Password Hash Synchronization permissions"
    GrantADPermissionsOnAllDomains -ACL $acls -Message $message -Inheritance $inheritanceNone -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for password write-back from Azure AD.
 
    .DESCRIPTION
        The Set-ADSyncPasswordWritebackPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Reset Password on descendant user objects
        2. Write Property access on lockoutTime attribute for all descendant user objects
        3. Write Property access on pwdLastSet attribute for all descendant user objects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER IncludeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncPasswordWritebackPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncPasswordWritebackPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncPasswordWritebackPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncPasswordWritebackPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncPasswordWritebackPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls = "`"$ADConnectorAccountSid" + ":CA;Reset Password;user`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":WP;lockoutTime;user`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":WP;pwdLastSet;user`""

    # Check if setting permissions on a AD object only
    $message = "Grant Password Writeback permissions"

    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncPasswordWritebackPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncPasswordWritebackPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg

        # Define Inheritance Type
        $objectInheritanceType = $inheritanceThisAndSubObjects
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            $objectInheritanceType = $inheritanceSubObjectsOnly
        }

        # Set AD Permissions on a target AD object
        Write-Verbose "Set-ADSyncPasswordWritebackPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$objectInheritanceType'..."
        GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

        # In case target ADObjectDN is a domain root, set Unexpire Password for the domain
        # Note: Unexpire Password permissions are only applicable on a domain root object (i.e. domainDNS objectClass)
        if ($object.objectclass -eq 'domainDNS')
        {
            # Define Inheritance Type for Unexpire Password
            $objectInheritanceType = $inheritanceThisAndSubObjects

            # Set ACL for Unexpire Password on the domain's root (domainDNS)
            $acls = "`"$ADConnectorAccountSid" + ":CA;Unexpire Password;`""
            $message = "Grant Password Writeback permission for Unexpire Password extended right"
            GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
        }
    }
    Else
    {
        # Set root permissions for all Domains in the Forest
        Write-Verbose "Set-ADSyncPasswordWritebackPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

        # Define Inheritance Type for Unexpire Password
        $objectInheritanceType = $inheritanceThisAndSubObjects

        # Set ACL for Unexpire Password on all domains in the forest
        $acls = "`"$ADConnectorAccountSid" + ":CA;Unexpire Password;`""
        $message = "Grant Password Writeback permission for Unexpire Password extended right"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -Inheritance $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for Group writeback from Azure AD.
 
    .DESCRIPTION
        The Set-ADSyncUnifiedGroupWritebackPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Generic Read/Write, Delete, Delete Tree and Create\Delete Child for Group Object types and SubObjects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
        In this case, ADobjectDN will be the Distinguished Name of the Container that you desire to link with the GroupWriteback feature.
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER includeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncUnifiedGroupWritebackPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncUnifiedGroupWritebackPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncUnifiedGroupWritebackPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncUnifiedGroupWritebackPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncUnifiedGroupWritebackPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Ensure the function is being run as Administrator
    $isRunningAsAdmin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
    If (!$isRunningAsAdmin)
    {
        Write-Error "This cmdlet must be run in an elevated PowerShell window."
        return
    }

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Check if setting permissions on a AD object only
    $message = "Grant Group Writeback permissions"

    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncUnifiedGroupWritebackPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncUnifiedGroupWritebackPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg        

        # Set AD Permissions on a target AD object and apply different inheritance flags as necessary
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            # Create/Delete Child group objects applies to the AD object and all children
            Write-Verbose "Set-ADSyncUnifiedGroupWritebackPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$inheritanceThisAndSubObjects'..."
            $acls  = "`"$ADConnectorAccountSid" + ":CCDC;group;`""
            GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $inheritanceThisAndSubObjects -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

            # Generic Read/Write, Delete object, and Delete tree applies to child inherited group objects of the AD object
            Write-Verbose "Set-ADSyncUnifiedGroupWritebackPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$inheritanceSubObjectsOnly'..."
            $acls = "`"$ADConnectorAccountSid" + ":GRGWSDDT;;group`""
            GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $inheritanceSubObjectsOnly -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
        }
        Else
        {
            Throw "Group writeback permissions can only be set on a Active Directory Domain, Organizational Unit or Container object."
        }
    }
    Else
    {
        # Define AD ACL
        # Create/Delete Child group objects applies to the AD object and all children
        $acls = "`"$ADConnectorAccountSid" + ":CCDC;group;`"" + " "
        # Generic Read/Write, Delete object, and Delete tree applies to child inherited group objects of the AD object
        $acls += "`"$ADConnectorAccountSid" + ":GRGWSDDT;;group`""

        # Set root permissions for all Domains in the Forest
        Write-Verbose "Set-ADSyncUnifiedGroupWritebackPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for mS-DS-ConsistencyGuid feature.
 
    .DESCRIPTION
        The Set-ADSyncMsDsConsistencyGuidPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Read/Write Property access on mS-DS-ConsistencyGuid attribute for all descendant user and group objects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER includeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncMsDsConsistencyGuidPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncMsDsConsistencyGuidPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncMsDsConsistencyGuidPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncMsDsConsistencyGuidPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncMsDsConsistencyGuidPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param(
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )    

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls = "`"$ADConnectorAccountSid" + ":RPWP;mS-DS-ConsistencyGuid;user`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RPWP;mS-DS-ConsistencyGuid;group`""

    # Check if setting permissions on a AD object only
    $message = "Grant mS-DS-ConsistencyGuid permissions"

    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncMsDsConsistencyGuidPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncMsDsConsistencyGuidPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg

        # Define Inheritance Type
        $objectInheritanceType = $inheritanceThisAndSubObjects
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            $objectInheritanceType = $inheritanceSubObjectsOnly
        }

        # Set AD Permissions on a target AD object
        Write-Verbose "Set-ADSyncMsDsConsistencyGuidPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$objectInheritanceType'..."
        GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
    Else
    {
        # Set root permissions for all Domains in the Forest
        Write-Verbose "Set-ADSyncMsDsConsistencyGuidPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for Exchange Mail Public Folder feature.
 
    .DESCRIPTION
        The Set-ADSyncExchangeMailPublicFolderPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Read Property access on all attributes for all descendant publicfolder objects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER includeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncExchangeMailPublicFolderPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncExchangeMailPublicFolderPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncExchangeMailPublicFolderPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncExchangeMailPublicFolderPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncExchangeMailPublicFolderPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param(
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls = "`"$ADConnectorAccountSid" + ":RP;;publicFolder`""

    # Check if setting permissions on a AD object only
    $message = "Grant Exchange Mail Public Folder permissions"
    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncExchangeMailPublicFolderPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncExchangeMailPublicFolderPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg

        # Define Inheritance Type
        $objectInheritanceType = $inheritanceThisAndSubObjects
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            $objectInheritanceType = $inheritanceSubObjectsOnly
        }

        # Set AD Permissions on a target AD object
        Write-Verbose "Set-ADSyncExchangeMailPublicFolderPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$objectInheritanceType'..."
        GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
    Else
    {
        # Set root permissions for all Domains in the Forest
        Write-Verbose "Set-ADSyncExchangeMailPublicFolderPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#.SYNOPSIS
        Initialize your Active Directory forest and domain for Exchange Hybrid feature.
 
    .DESCRIPTION
        The Set-ADSyncExchangeHybridPermissions Function will give required permissions to the
        AD synchronization account, which include the following:
        1. Read/Write Property access on all attributes for all descendant user objects
        2. Read/Write Property access on all attributes for all descendant inetOrgPerson objects
        3. Read/Write Property access on all attributes for all descendant group objects
        4. Read/Write Property access on all attributes for all descendant contact objects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER includeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncExchangeHybridPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncExchangeHybridPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncExchangeHybridPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncExchangeHybridPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncExchangeHybridPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    
    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls  = "`"$ADConnectorAccountSid" + ":RPWP;;user`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RPWP;;inetOrgPerson`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RPWP;;group`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RPWP;;contact`""

    # Check if setting permissions on a AD object only
    $message = "Grant Exchange Hybrid permissions"
    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncExchangeHybridPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncExchangeHybridPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg

        # Define Inheritance Type
        $objectInheritanceType = $inheritanceThisAndSubObjects
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            $objectInheritanceType = $inheritanceSubObjectsOnly
        }

        # Set AD Permissions on a target AD object
        Write-Verbose "Set-ADSyncExchangeHybridPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$objectInheritanceType'..."
        GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
    Else
    {
        # Set root permissions for all Domains in the Forest
        Write-Verbose "Set-ADSyncExchangeHybridPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#
    .SYNOPSIS
        Initialize your Active Directory forest and domain for basic read permissions.
 
    .DESCRIPTION
        The Set-ADSyncBasicReadPermissions Function will give required permissions to the AD synchronization account, which include the following:
        1. Read Property access on all attributes for all descendant computer objects
        2. Read Property access on all attributes for all descendant device objects
        3. Read Property access on all attributes for all descendant foreignsecurityprincipal objects
        5. Read Property access on all attributes for all descendant user objects
        6. Read Property access on all attributes for all descendant inetOrgPerson objects
        7. Read Property access on all attributes for all descendant group objects
        8. Read Property access on all attributes for all descendant contact objects
 
        These permissions are applied to all domains in the forest.
        Optionally you can provide a DistinguishedName in ADobjectDN parameter to set these permissions on that AD Object only (including inheritance to sub objects).
 
    .PARAMETER ADConnectorAccountName
        The Name of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDomain
        The Domain of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER ADConnectorAccountDN
        The DistinguishedName of the Active Directory account that is or will be used by Azure AD Connect Sync to manage objects in the directory.
 
    .PARAMETER includeAdminSDHolders
        Optional parameter to indicate if AdminSDHolder container should be updated with these permissions
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
       Set-ADSyncBasicReadPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com'
 
    .EXAMPLE
       Set-ADSyncBasicReadPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com'
 
    .EXAMPLE
       Set-ADSyncBasicReadPermissions -ADConnectorAccountDN 'CN=ADConnector,OU=AzureAD,DC=Contoso,DC=com' -IncludeAdminSDHolders
 
    .EXAMPLE
       Set-ADSyncBasicReadPermissions -ADConnectorAccountName 'ADConnector' -ADConnectorAccountDomain 'Contoso.com' -ADobjectDN 'OU=AzureAD,DC=Contoso,DC=com'
#>

Function Set-ADSyncBasicReadPermissions
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param(
        # AD Connector Account Name used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountName,

        # AD Connector Account Domain used by Azure AD Connect Sync
        [Parameter(ParameterSetName='UserDomain', Mandatory=$True)]
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDomain,

        # AD Connector Account DistinguishedName used by Azure AD Connect Sync
        [Parameter(ParameterSetName='DistinguishedName', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $ADConnectorAccountDN,

        # DistinguishedName of the target AD object to set permissions (optional)
        [string] $ADobjectDN = $null,
        
        # Update permissions on the AdminSdHolders container (optional)
        [switch] $IncludeAdminSDHolders = $false,

        # Forest to set the permissions on
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        # Credentials used to configure the permissions
        [Parameter(ParameterSetName='UserDomainWithCredential', Mandatory=$True)]
        [Parameter(ParameterSetName='DistinguishedNameWithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Resolve AD Connector account identity on AD
    $ADConnectorIdentity = ResolveADobject -IdentityName $ADConnectorAccountName -IdentityDomain $ADConnectorAccountDomain -IdentityDN $ADConnectorAccountDN `
                            -IdentityParameterSet $($PSCmdlet.ParameterSetName) -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    $ADConnectorAccountSid = $ADConnectorIdentity.objectSid

    # Define AD ACL
    $acls =  "`"$ADConnectorAccountSid" + ":RP;;computer`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;device`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;foreignsecurityprincipal`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;user`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;inetOrgPerson`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;group`"" + " "
    $acls += "`"$ADConnectorAccountSid" + ":RP;;contact`""
    
    # Check if setting permissions on a AD object only
    $message = "Grant basic read permissions"
    If (![string]::IsNullOrEmpty($ADobjectDN))
    {
        # Get target AD Object
        Write-Verbose "Set-ADSyncBasicReadPermissions: Get AD user object > Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * "
        $errorMsg = "Set-ADSyncBasicReadPermissions: Unable to find Active Directory object '$ADobjectDN'. "
        $object = Get-ADSyncADObject $ADobjectDN $errorMsg

        # Define Inheritance Type
        $objectInheritanceType = $inheritanceThisAndSubObjects
        If (($object.objectclass -eq 'container') -or ($object.objectclass -eq 'organizationalUnit') -or ($object.objectclass -eq 'domainDNS'))
        {
            $objectInheritanceType = $inheritanceSubObjectsOnly
        }

        # Set AD Permissions on a target AD object
        Write-Verbose "Set-ADSyncBasicReadPermissions: Calling GrantADPermissionsOnADobject on target object '$ADobjectDN' with inheritanceType = '$objectInheritanceType'..."
        GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -InheritanceType $objectInheritanceType -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

        # In case target ADObjectDN is a domain root, set Replicating Directory Changes/All permission for the domain
        # Note: Replicating Directory Changes/All permissions are only applicable on a domain root object (i.e. domainDNS objectClass)
        if ($object.objectclass -eq 'domainDNS')
        {
            # Set Replicating Directory Changes root permission for all Domains in the Forest.
            $acls = "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes`"" + " "
            $acls += "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes All`""

            $message += " > replicating directory changes"
            Write-Verbose "Set-ADSyncBasicReadPermissions: Calling GrantADPermissionsOnADobject for 'Replicating Directory Changes' permissions on target object '$ADobjectDN'"
            GrantADPermissionsOnADobject -ACL $acls -ADobjectDN $ADobjectDN -Message $message -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
        }
    }
    Else
    {
        # Set root permissions for all Domains in the Forest.
        Write-Verbose "Set-ADSyncBasicReadPermissions: Calling GrantADPermissionsOnAllDomains on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -IncludeAdminSDHolders:$IncludeAdminSDHolders -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

        # Set Replicating Directory Changes/All root permissions for all Domains in the Forest.
        # Note: Replicating Directory Changes/All permissions are only applicable on a domain root object (i.e. domainDNS objectClass)
        $acls = "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes`"" + " "
        $acls += "`"$ADConnectorAccountSid" + ":CA;Replicating Directory Changes All`""

        $functionMsg = 'Grant permissions on all Domains:'
        $message += " > replicating directory changes"
        Write-Verbose "Set-ADSyncBasicReadPermissions: Calling GrantADPermissionsOnAllDomains for 'Replicating Directory Changes' permissions on all domain's root"
        GrantADPermissionsOnAllDomains -ACL $acls -Message $message -Inheritance $inheritanceNone -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    }
}

<#
    .SYNOPSIS
        Gets AD objects with permission inheritance disabled
 
    .DESCRIPTION
        Searches in AD starting from the SearchBase parameter and returns all objects, filtered by ObjectClass parameter, that have the ACL Inheritance currently disabled.
 
    .PARAMETER SearchBase
        The SearchBase for the LDAP query that can be an AD Domain DistinguishedName or a FQDN
 
    .PARAMETER ObjectClass
        The class of the objects to search that can be '*' (for any object class), 'user', 'group', 'container', etc. By default, this function will search for 'organizationalUnit' object class.
 
    .PARAMETER TargetForest
        Optional parameter to configure a target forest instead of the one used by the current user context.
 
    .PARAMETER TargetForestCredential
        Required if the TargetForest parameter is used. Credentials that will be used to perform operations on the target forest.
 
    .EXAMPLE
        Find objects with disabled inheritance in 'Contoso' domain (by default returns 'organizationalUnit' objects only)
        Get-ADSyncObjectsWithInheritanceDisabled -SearchBase 'Contoso'
 
    .EXAMPLE
        Find 'user' objects with disabled inheritance in 'Contoso' domain
        Get-ADSyncObjectsWithInheritanceDisabled -SearchBase 'Contoso' -ObjectClass 'user'
 
    .EXAMPLE
        Find all types of objects with disabled inheritance in a OU
        Get-ADSyncObjectsWithInheritanceDisabled -SearchBase OU=AzureAD,DC=Contoso,DC=com -ObjectClass '*'
#>

Function Get-ADSyncObjectsWithInheritanceDisabled
{
    [CmdletBinding()]
    Param
    (
        [Parameter(ParameterSetName='WithoutCredential', Mandatory=$True,Position=0)]
        [Parameter(ParameterSetName='WithCredential', Mandatory=$True,Position=0)]
        [String] $SearchBase,

        [Parameter(Mandatory=$False,Position=1)] 
        [String] $ObjectClass = 'organizationalUnit',

        [Parameter(ParameterSetName='WithCredential', Mandatory=$True)]
        [string] $TargetForest = $null,

        [Parameter(ParameterSetName='WithCredential', Mandatory=$True)]
        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Function init
    [string] $functionMsg = "Get-ADSyncObjectsWithInheritanceDisabled:"

    Try
    {
        # Init a DirectorySearcher object
        If ($TargetForest)
        {
            $networkCredential = $TargetForestCredential.GetNetworkCredential()

            $directoryEntry = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$TargetForest/$SearchBase", $TargetForestCredential.UserName, $networkCredential.Password)

            $ldapFilter = "(&(ObjectClass=$ObjectClass))"
            $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher($directoryEntry, $ldapFilter)
            $directorySearcher.PageSize = 1000
        }
        Else
        {
            $ldapFilter = "(&(ObjectClass=$ObjectClass))"
            $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"LDAP://$SearchBase", $ldapFilter)
            $directorySearcher.PageSize = 1000
        }
    }
    Catch
    {
        Throw "$functionMsg Unable to search Active Directory. Error Details: $($_.Exception.Message)"
    }

    Try
    {
        # Search All Objects
        Write-Verbose "$functionMsg Searching for objects in AD with LDAP Filter: $ldapFilter"
        $allADobjects = $directorySearcher.FindAll()
    }
    Catch
    {
        Throw "$functionMsg Unable to query Active Directory. Error Details: $($_.Exception.Message)"
    }
    Finally
    {
        If ($directorySearcher -ne $null)
        {
            $directorySearcher.Dispose()
        }

        If ($directoryEntry -ne $null)
        {
            $directoryEntry.Dispose()
        }
    }

    # Check if Inheritance is Disabled
    Foreach ($object in $allADobjects) 
    {
        $object = $object.GetDirectoryEntry()
        Write-Verbose "$functionMsg $($object.DistinguishedName)"
        If ($object.ObjectSecurity.AreAccessRulesProtected -eq $True)
        {
            ResolveADobject -IdentityDN $object.DistinguishedName -IdentityParameterSet 'DistinguishedName' -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
        }
    }
}

<#
.Synopsis
   Shows permissions of a specified AD object.
.DESCRIPTION
   This function retuns all the AD permissions currently set for a given AD object provided in the parameter -ADobjectDN.
   The ADobjectDN must be provided in a DistinguishedName format.
 .PARAMETER TargetForestCredential
   Optional paramter if the target object is on a different forest than the current user context.
.EXAMPLE
   Show-ADSyncADObjectPermissions -ADobjectDN 'DC=Contoso,DC=com'
#>

Function Show-ADSyncADObjectPermissions
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [string] $ADobjectDN,

        [System.Management.Automation.PSCredential] $TargetForestCredential = $null
    )

    # Function init
    [string] $functionMsg = "Get-ADSyncADObjectPermissions:"

    # See more on dsacls.exe here: https://ss64.com/nt/dsacls.html
    $cmd = "dsacls.exe `"$ADobjectDN`""
    Write-Verbose "$functionMsg Executing command : $cmd"

    If ($TargetForestCredential)
    {
        $networkCredential = $TargetForestCredential.GetNetworkCredential()

        $domain = $networkCredential.Domain
        $user = $networkCredential.UserName
        $passwd = $networkCredential.Password

        $passwd = ReplaceReservedCharcters -PreReplace $passwd

        $result = dsacls.exe "`"$ADobjectDN`"" /domain:"`"$domain"`" /user:"`"$user"`" /passwd:"`"$passwd`""
    }
    Else
    {
        $result = dsacls.exe "`"$ADobjectDN`""
    }

    If ($lastexitcode -eq 0)
    {
        $result
    }
    Else
    {
        Throw "$functionMsg $result"
    }
}

<#
.Synopsis
   Gets the account name and domain that is configured in each AD Connector
.DESCRIPTION
   This function uses the 'Get-ADSyncConnector' cmdlet that is present in AAD Connect to retrieve from Connectivity Parameters a table showing the AD Connector(s) account.
.EXAMPLE
   Get-ADSyncADConnectorAccount
#>

Function Get-ADSyncADConnectorAccount
{
    [CmdletBinding()]
    $cmdlet = 'Get-ADSyncConnector'
    Try
    {
        Get-Command $cmdlet -ErrorAction Stop | Out-Null
    }
    Catch
    {
        Write-Error "Failure calling '$cmdlet' cmdlet. This function can only be executed with AAD Connect installed."
        Return $null
    }

    $adConnectors = Get-ADSyncConnector | where {$_.ConnectorTypeName -eq 'AD'}
    $adSyncADConnectorAccount = @()
    ForEach ($connector in $adConnectors)
    {
        $connectorAccount = "" | Select ADConnectorName, ADConnectorForest, ADConnectorAccountName, ADConnectorAccountDomain
        $connectorAccount.ADConnectorName = $connector.Name
        $connectorAccount.ADConnectorForest = ($connector.ConnectivityParameters | Where {$_.Name -eq 'forest-name'}).Value
        $connectorAccount.ADConnectorAccountName = ($connector.ConnectivityParameters | Where {$_.Name -eq 'forest-login-user'}).Value
        $connectorAccount.ADConnectorAccountDomain = ($connector.ConnectivityParameters | Where {$_.Name -eq 'forest-login-domain'}).Value
        $adSyncADConnectorAccount += $connectorAccount
    }
    $adSyncADConnectorAccount

}


# Gets an object from Active Directory based on its DN
Function Get-ADSyncADObject
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [string] $ADobjectDN,

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

    # Get target AD Object
    Try
    {
        Get-ADObject -SearchBase $ADobjectDN -SearchScope Base -Filter * -ErrorAction Stop
    }
    Catch [Microsoft.ActiveDirectory.Management.ADReferralException]
    {
        $ErrorMsg += "Try logging in with a Domain Administrator account in the same domain as the target object or use TargetForest/TargetForestCredential parameters. "
        Throw $ErrorMsg += "Error Details: $($_.Exception.Message)"
    }
    Catch
    {
        Throw $ErrorMsg += "Error Details: $($_.Exception.Message)"
    }

}

# Grants permissions to specified ObjectDN
Function GrantAcls
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [string] $ObjectDN,

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

        [Parameter(Mandatory=$True,Position=2)] 
        [char] $InheritFlag,

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )

    # See more on dsacls.exe here: https://ss64.com/nt/dsacls.html
    If ($TargetForestCredential)
    {
        $networkCredential = $TargetForestCredential.GetNetworkCredential()

        $domain = $networkCredential.Domain
        $user = $networkCredential.UserName
        $passwd = $networkCredential.Password

        If (!$domain) 
        {
            Write-Error "You must enter your Administrator credentials in a domain.com\username format."
            return
        }

        $passwd = ReplaceReservedCharcters -PreReplace $passwd
        
        $cmd = "dsacls.exe `"$ObjectDN`" /G $ACLs /I:$InheritFlag /domain:`"$domain`" /user:`"$user`""
        $cmdExecute = $cmd + " /passwd:`"$passwd`""
        $cmdTrace = $cmd + " /passwd:`"********`""
        Write-Verbose "Grant ACLs : Executing command : $cmdTrace"

        $result = Invoke-Expression $cmdExecute
    }
    Else
    {
        $cmd = "dsacls.exe `"$ObjectDN`" /G $ACLs /I:$InheritFlag"
        Write-Verbose "Grant ACLs : Executing command : $cmd"

        $result = Invoke-Expression $cmd
    }

    If ($lastexitcode -eq 0)
    {
        $result
        Write-Warning "You will need to perform a full import to include any objects that may have come in scope as a result of this operation."
    }
    Else
    {
        $noExchangeShemaError = $result | Where {$_ -like "*No GUID Found for publicFolder*"}
        If (($noExchangeShemaError | Measure-Object).Count -gt 0)
        {
            Write-Error "AD Schema for Exchange not present : $result"
        }
        Else
        {
            Write-Error "$result"
        }
    }
}

# Grants permissions to specified ObjectDN
Function GrantAclsNoInheritance
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [string] $ObjectDN,

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

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )

    # See more on dsacls.exe here: https://ss64.com/nt/dsacls.html
    If ($TargetForestCredential)
    {
        $networkCredential = $TargetForestCredential.GetNetworkCredential()

        $domain = $networkCredential.Domain
        $user = $networkCredential.UserName
        $passwd = $networkCredential.Password

        If (!$domain) 
        {
            Write-Error "You must enter your Administrator credentials in a domain.com\username format."
            return
        }

        $passwd = ReplaceReservedCharcters -PreReplace $passwd

        $cmd = "dsacls.exe `"$ObjectDN`" /G $ACLs /domain:`"$domain`" /user:`"$user`""
        $cmdExecute = $cmd + " /passwd:`"$passwd`""
        $cmdTrace = $cmd + " /passwd:`"********`""
        Write-Verbose "Grant ACLs without Inheritance : Executing command : $cmdTrace"

        $result = Invoke-Expression $cmdExecute
    }
    Else
    {
        $cmd = "dsacls.exe `"$ObjectDN`" /G $ACLs"
        Write-Verbose "Grant ACLs without Inheritance : Executing command : $cmd"

        $result = Invoke-Expression $cmd
    }

    If ($lastexitcode -eq 0)
    {
        $result
        Write-Warning "You will need to perform a full import to include any objects that may have come in scope as a result of this operation."
    }
    Else
    {
        Write-Error "$result"
    }

}

# Converts a FQDN to domain DistinguishedName
Function ConvertFQDNtoDN
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [String] 
        $FQDN
    )

    # Init of variable is required to prevent use of a session variable.
    $dn = ""

    # Convert each period separated domain name into a DistinguishedName
    ForEach ($domain in $($FQDN.Split($periodSeparator)))
    {
        $dn = $dn + $connector + "DC=" + $domain
        $connector = $commaSeparator
    }
    Return $dn
}

# Converts a domain DistinguishedName to FQDN
Function ConvertDNtoFQDN
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [String] 
        $DN
    )

    # Init of variable is required to prevent use of a session variable.
    $fqdn = ""

    # Convert each commma separated domain into a FQDN
    ForEach ($domain in $($DN  -split $commaSeparator))
    {
        $fqdn += "$($domain.Substring(3))."
    }
    
    # Remove the last dot
    $fqdn = $fqdn.Substring(0,$fqdn.Length -1)
    
    Return $fqdn
}

# Get list of Domains in the Forest
Function GetADDomains
{
    [CmdletBinding()]
    Param(
        [String] $TargetForest,

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )

    # Function init
    [string] $functionMsg = "Get AD Domains:"
    
    Try
    {
        If ($TargetForestCredential)
        {
            Write-Verbose "$functionMsg Retrieving list of Domains in Forest '$TargetForest'..."
            $forest = Get-ADForest -Identity $TargetForest -Credential $TargetForestCredential -ErrorAction Stop
        }
        Else
        {
            Write-Verbose "$functionMsg Retrieving list of Domains in the Forest..."
            $forest = Get-ADForest -ErrorAction Stop
        }
    }
    Catch
    {
        Throw "$functionMsg Unable to get list of Domains in the Forest. Exception Details: $($_.Exception.Message)"
    }

    Return $($forest.Domains)
}


Function ResolveADobject
{
    [CmdletBinding()]
    Param
    (
        [string] $IdentityName,

        [string] $IdentityDomain,

        [string] $IdentityDN,

        [string] $IdentityParameterSet,

        [switch] $ReturnADobject,

        [string] $TargetForest,

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )
    
    # Check if AD PowerShell Module is installed
    ImportADmodule

    # Init
    [string] $functionMsg = "Resolve AD object:"
    Write-Verbose "ParameterSetName: $IdentityParameterSet"

    switch ($IdentityParameterSet)
    {
        {($_ -eq 'UserDomain') -or ($_ -eq 'UserDomainWithCredential')}
        {
            # Search for AD object using object name and target domain
            Write-Verbose "$functionMsg Resolving AD object '$IdentityName' in Domain '$IdentityDomain'..."
            Try
            {   
                If ($TargetForestCredential)
                {
                    $targetDomain = Get-ADDomain -Identity $IdentityDomain -Credential $TargetForestCredential -ErrorAction Stop
                }
                Else
                {
                    $targetDomain = Get-ADDomain -Identity $IdentityDomain -ErrorAction Stop
                }
            }
            Catch
            {
                Throw "$functionMsg Unable to find Domain '$IdentityDomain' in AD Forest. Exception Details: $($_.Exception.Message)"
            }

            $ldapFilter = "(|(Name=$IdentityName)(sAMAccountName=$IdentityName))"
            $targetDomainDNSname = $targetDomain.DNSRoot
            Write-Verbose "$functionMsg LDAP Filter to search object: $ldapFilter"
            Write-Verbose "$functionMsg Target Domain to search object: $targetDomainDNSname"

            Try
            {
                If ($TargetForestCredential)
                {
                    $adObject = Get-ADObject -LDAPFilter $ldapFilter -Server $targetDomainDNSname -Properties $defaultADobjProperties -Credential $TargetForestCredential -ErrorAction Stop
                }
                Else
                {
                    $adObject = Get-ADObject -LDAPFilter $ldapFilter -Server $targetDomainDNSname -Properties $defaultADobjProperties -ErrorAction Stop
                }
            }
            Catch
            {
                Throw "$functionMsg Unable to get object '$IdentityName' in AD Forest. Exception Details: $($_.Exception.Message)"
            }
        }
        {($_ -eq 'DistinguishedName') -or ($_ -eq 'DistinguishedNameWithCredential')}
        {
            # Search for AD object using DistinguishedName against an AD Global Catalog (AD Forest wide search)
            Write-Verbose "$functionMsg Resolving AD object DN $IdentityDN..."
            # Encode reserved characters to Hex values
            $IdentityDN = Convert-DNtoHex $IdentityDN
            If ($IdentityDN -match $distinguishedNameRegex)
            {
                Write-Verbose "$functionMsg Matches in DistinguishedName input: $($Matches.Values | %{"$_;"})"
                $IdentityDomainDN = $Matches.domain
                $IdentityName = $Matches.name

                Try
                {
                    # Get an array of Domain Controllers running Global Catalog service
                    $globalCatalogSrv = @(Get-ADDomainController -Discover -DomainName $TargetForest -Service GlobalCatalog -ErrorAction Stop)
                }
                Catch
                {
                    Throw "$functionMsg Unable to find a Global Catalog DC in AD. Exception Details: $($_.Exception.Message)"
                }
    
                If (($globalCatalogSrv | Measure-Object).Count -gt 0)
                {
                    # Pick the first DC in the array and add the GC port
                    $globalCatalogHost = [string] $globalCatalogSrv[0].HostName[0].ToString() + ":3268"
                    Write-Verbose "$functionMsg Target Global Catalog Server to search object: $globalCatalogHost"
                }
                Else
                {
                    Throw "$functionMsg Could not find any available Global Catalog DC in AD."
                }

                Try
                {
                    # Get the AD object based on the DistinguishedName from a GC server in AD
                    If ($TargetForestCredential)
                    {
                        $adObject = Get-ADObject -Identity $IdentityDN -Server $globalCatalogHost -Properties $defaultADobjProperties -Credential $TargetForestCredential -ErrorAction Stop
                    }
                    Else
                    {
                        $adObject = Get-ADObject -Identity $IdentityDN -Server $globalCatalogHost -Properties $defaultADobjProperties -ErrorAction Stop
                    }
                }
                Catch
                {
                    Throw "$functionMsg Unable to get object '$IdentityDN' in AD Forest. Exception Details: $($_.Exception.Message)"
                }

                # If going to return Domain\Username, need to get the AD Domain object
                If (-not $ReturnADobject)
                {
                    $IdentityDomain = ConvertDNtoFQDN $IdentityDomainDN

                    Try
                    {
                        Write-Verbose "$functionMsg Resolving AD Domain '$IdentityDomain'..."

                        If ($TargetForestCredential)
                        {
                            $targetDomain = Get-ADDomain -Identity $IdentityDomain -Credential $TargetForestCredential -ErrorAction Stop
                        }
                        Else
                        {
                            $targetDomain = Get-ADDomain -Identity $IdentityDomain -ErrorAction Stop
                        }
                    }
                    Catch
                    {
                        Throw "$functionMsg Unable to find Domain '$IdentityDomain' in AD Forest. Exception Details: $($_.Exception.Message)"
                    }
                }
            }
            Else
            {
                Throw "$functionMsg Cannot validate argument on parameter 'ADConnectorAccountDN'. The argument '$IdentityDN' does not match a DistinguishedName format."
            }
        }
    }

    # If found, return the identity
    If ($adObject -ne $null)
    {
        If ($ReturnADobject) 
        {
            # Return AD object
            Write-Verbose "$functionMsg Returning AD object: $($adObject.Name)"
            Return $adObject
        }
        Else
        {
            # Get the domain NetBIOS name and return Domain\Username
            $targetDomainNetBIOS = $targetDomain.NetBIOSName
            $targetUsername = $adObject.sAMAccountName
            Write-Verbose "$functionMsg Returning NetBIOS Domain name: $targetDomainNetBIOS"
            Write-Verbose "$functionMsg Returning Username: $targetUsername"
            $identity = [String] $targetDomainNetBIOS + "\" + $targetUsername
            Return $identity
        }
    }
    Else
    {
        Throw "$functionMsg Unable to find '$IdentityName' in AD Forest."
    }
}

# Sets permissions on a target AD object
Function GrantADPermissionsOnADobject
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD permission ACEs to set
        [Parameter(Mandatory=$True)] 
        [ValidateNotNullOrEmpty()] 
        [String] $ACL,

        # DistinguishedName of the target AD object to set permissions
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()] 
        [String] $ADobjectDN,

        # Permissions description message for console output
        [String] $Message = "Grant Active Directory Permissions",

        # Set permission Inheritance for AD objects - Defaults to 'This object and subobjects'
        [String] $InheritanceType = $inheritanceThisAndSubObjects,

        [String] $TargetForest,

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )

    # Function init
    ImportADmodule
    [string] $functionMsg = "Grant permissions on AD object:"
    Write-Verbose "$functionMsg AD permissions ACEs to add: $ACL"

    # Search for AD object using DistinguishedName
    $targetADObj = ResolveADobject -IdentityDN $ADobjectDN -IdentityParameterSet 'DistinguishedName' -ReturnADobject -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential
    $targetADObjClass = $targetADObj.ObjectClass
    Write-Verbose "$functionMsg Target AD Object Class: $targetADObjClass"

    # Set inheritance type
    $Inheritance = $inheritanceType

    If ($targetADObjClass -eq 'organizationalUnit' -or $targetADObjClass -eq 'container' -or $targetADObjClass -eq 'domainDNS')
    {
        # Set permissions for standard object types
        $finalACL = $ACL
    }
    Else
    {
        # Adapt ACL to target the specific AD object
        $ACEarray = $ACL -split $aclSeparator
        $targetADObjACL = @()

        # For each ACE, check if applies to an ObjectClass and if the ObjectClass matches the target AD object
        ForEach ($ace in $ACEarray)
        {
            $indexOfObjClass = $ace.LastIndexOf(";")
            If ($indexOfObjClass -lt 0)
            {
                # No ObjectClass defined in ACE - applies to all objects
                $targetADObjACL += $ace
            }
            Else
            {
                # Specific ObjectClass defined in ACE - applies only if the same as the target object
                $aceTargetClass = $ace.Substring($indexOfObjClass)
                If ($aceTargetClass.Contains($targetADObjClass))
                {
                    # Take this ACE but remove the InheritedObjectType since we will apply ACL to a non-container object
                    $targetADObjACL += $ace -replace ";$targetADObjClass", ""
                }
            }
        }

        # Finalize the filtered ACEs for the target AD object
        If (($targetADObjACL | Measure-Object).Count -eq 0)
        {
             Throw "$functionMsg Permissions are not applicable to AD ObjectClass '$targetADObjClass': $ACL"
        }
        Else
        {
            # Glue all the ACEs in a string back again separated by $aclSeparator
            $finalACL = $null
            for ($i = 0; $i -lt $targetADObjACL.Count-1; $i++)
            { 
                $finalACL += [String] $targetADObjACL[$i]+ $aclSeparator
            }
            $finalACL += [String] $targetADObjACL[$targetADObjACL.Count-1]
        }
        
        # Enclose all the ACEs in double quotes
        If ($finalACL[0] -ne '"') 
        {
            $finalACL =  '"' + $finalACL
        }
        If ($finalACL[$finalACL.Length-1] -ne '"') 
        {
            $finalACL =  $finalACL + '"'
        }
        Write-Verbose  "$functionMsg AD permissions ACEs for target AD object: $finalACL"
    }

    # Set AD Permissions on a target AD object
    If ($PSCmdlet.ShouldProcess($targetADObj.Name, $Message)) 
    {
        Write-Output "$functionMsg Setting permissions on AD object '$($targetADObj.DistinguishedName)'..."
        GrantAcls $targetADObj.DistinguishedName $finalACL $Inheritance -TargetForestCredential $TargetForestCredential
    }
    Else
    {
        Write-Verbose "$functionMsg Operation canceled."
    }
}

# Sets permissions on all Domains in the Forest
Function GrantADPermissionsOnAllDomains
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="high")]
    Param
    (
        # AD permission ACEs to set
        [Parameter(Mandatory=$True)] 
        [ValidateNotNullOrEmpty()] 
        [String] $ACL,

        # Update permissions on the AdminSdHolders container
        [Switch] $IncludeAdminSDHolders,

        # Permission Inheritance
        [String] $Inheritance = $inheritanceSubObjectsOnly,

        # Permissions description message for console output
        [String] $Message = "Grant Active Directory Permissions",

        [String] $TargetForest,

        [System.Management.Automation.PSCredential] $TargetForestCredential
    )

    # Function init
    ImportADmodule
    [string] $functionMsg = "Grant permissions on all Domains:"
    Write-Verbose "$functionMsg AD permissions ACEs to add: $ACL"

    # Get list of all Domains in the Forest
    $domains = GetADDomains -TargetForest $TargetForest -TargetForestCredential $TargetForestCredential

    # Set root permissions for all Domains in the Forest
    ForEach($domain in $domains) 
    {
        If ($PSCmdlet.ShouldProcess($domain, $Message)) 
        {
            $domainDN = ConvertFQDNtoDN -FQDN $domain
            Write-Output "$functionMsg AD Domain '$domainDN'..."
            If ($Inheritance -eq $inheritanceNone)
            {
                GrantAclsNoInheritance $domainDN $ACL -TargetForestCredential $TargetForestCredential
            }
            Else
            {
                GrantAcls $domainDN $ACL $Inheritance -TargetForestCredential $TargetForestCredential
            }

            # Check if setting permissions on AdminSdHolder container
            If ($IncludeAdminSDHolders) 
            {
                Try 
                {
                    Write-Output "$functionMsg Setting permissions on AdminSDHolder container of '$domainDN'"

                    If ($TargetForestCredential)
                    {
                        $adminSDHolderDN = (Get-ADObject -Server $domain -Filter "Name -like 'adminsdholder'" -Credential $TargetForestCredential).DistinguishedName
                    }
                    Else
                    {
                        $adminSDHolderDN = (Get-ADObject -Server $domain -Filter "Name -like 'adminsdholder'").DistinguishedName
                    }
                }
                Catch 
                {
                    Throw "$functionMsg Unable to get AdminSDHolder container of '$domainDN'. Exception details: $($_.Exception)"
                }
                # Setting permissions on AdminSdHolder container
                GrantAcls $adminSDHolderDN $ACL $Inheritance -TargetForestCredential $TargetForestCredential
            }
        }
        Else
        {
            Write-Verbose "$functionMsg Operation canceled."
        }
    }
}

Function TestCredential
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)] 
        [System.Management.Automation.PSCredential] $Credential
    )

    # Function init
    [string] $functionMsg = "Test Credential:"
    $networkCredential = $Credential.GetNetworkCredential()

    If ($networkCredential.UserName.Contains("@") -or $networkCredential.Domain.ToString() -eq "")
    {
        Throw [System.ArgumentException] "$functionMsg Validating credential parameter failed. Credential should use the fully qualified domain name of the administrator account. Example: CONTOSO\admin"
    }
    
    Try
    {
        # $Credential.UserName == FQDN\Username, $networkCredential.UserName == just the Username portion. We need to use the FQDN from here
        $dc = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain, $networkCredential.Domain, $Credential.UserName, $networkCredential.Password) -ErrorAction Stop
    }
    Catch
    {
        Throw [System.ArgumentException] "$functionMsg Validating credential parameter failed. Unable to use credentials to access AD. Error Details: $($_.Exception.Message)"
    }

    Try
    {
        # Validating credential
        $credentialValid = $false
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($dc)
        $enterpriseAdminsSid = GetEnterpriseAdminsSid $Credential
        $domainAdminsSid = GetDomainAdminsSid $Credential

        $domainDE = $domain.GetDirectoryEntry()
        $searchFilter = "(samAccountName=$($networkCredential.UserName))"
        $directorySearcher = New-Object System.DirectoryServices.DirectorySearcher($domainDE, $searchFilter)

        $searchResult = $directorySearcher.FindOne()
        If ($searchResult -eq $null)
        {
            Throw [System.ArgumentException] "$functionMsg Validating credential parameter failed. Admin account '$($Credential.UserName)' could not be found."
        }

        $adminDE = $searchResult.GetDirectoryEntry()

        [string[]] $propertyName = @("tokenGroups")
        $adminDE.RefreshCache($propertyName)
        ForEach ($resultBytes in $adminDE.Properties["tokenGroups"])
        {
            $sid = New-Object System.Security.Principal.SecurityIdentifier($resultBytes, 0)
            If ($sid.Equals($enterpriseAdminsSid) -or $sid.Equals($domainAdminsSid))
            {
                $credentialValid = $true
                Break
            }
        }

        If (!$credentialValid)
        {
            Throw [System.ArgumentException] "$functionMsg Validating credential parameter failed. Enterprise Admin or Domain Admin credential is required to restrict permissions on the account."
        }
    }
    Catch [Exception]
    {
        Throw "$functionMsg Validating credential parameter failed. Error Details: $($_.Exception.Message)"
    }
    Finally
    {
        # Clean up memory
        If ($domain -ne $null)
        {
            $domain.Dispose()
        }

        If ($domainDE -ne $null)
        {
            $domainDE.Dispose()
        }

        If ($directorySearcher -ne $null)
        {
            $directorySearcher.Dispose()
        }

        If ($adminDE -ne $null)
        {
            $adminDE.Dispose()
        }
    }
}

Function GetEnterpriseAdminsSid
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True)] 
        [System.Management.Automation.PSCredential] $Credential
    )

    $networkCredential = $Credential.GetNetworkCredential()
    $dc = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain, $networkCredential.Domain, $Credential.UserName, $networkCredential.Password)            

    try
    {
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($dc)        
        try
        {
            $de = $domain.Forest.RootDomain.GetDirectoryEntry()
            $rootDomainSidInBytes = $de.Properties["ObjectSID"].Value
            $domainSid = New-Object System.Security.Principal.SecurityIdentifier($rootDomainSidInBytes, 0)
            $eaSid = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::AccountEnterpriseAdminsSid, $domainSid)
            return $eaSid
        }
        finally
        {
            if ($de -ne $null)
            {
                $de.Dispose()
            }
        }
    }
    finally
    {
        if ($domain -ne $null)
        {
            $domain.Dispose()
        }
    }
}

Function GetDomainAdminsSid
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True)] 
        [System.Management.Automation.PSCredential] $Credential
    )

    $networkCredential = $Credential.GetNetworkCredential()
    $dc = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext([System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain, $networkCredential.Domain, $Credential.UserName, $networkCredential.Password)

    try
    {
        $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($dc)        
        try
        {
            $de = $domain.GetDirectoryEntry()
            $domainSidInBytes = $de.Properties["ObjectSID"].Value
            $domainSid = New-Object System.Security.Principal.SecurityIdentifier($domainSidInBytes, 0)
            $domainAdminsSid = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::AccountDomainAdminsSid, $domainSid)
            return $domainAdminsSid
        }
        finally
        {
            if ($de -ne $null)
            {
                $de.Dispose()
            }
        }
    }
    finally
    {
        if ($domain -ne $null)
        {
            $domain.Dispose()
        }
    }
}

# Convert SIDs to readable names
Function ConvertSIDtoName
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] 
        [string] $SID
    )

    $ID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $sid
    $User = $ID.Translate([System.Security.Principal.NTAccount])
    $User.Value
}

# Confirm if ActiveDirectory PowerShell Module is present and load it
Function ImportADmodule
{
    [CmdletBinding()]
    Param()

    If (-not (Get-Module ActiveDirectory))
    {
        Try
        {
            # Load ActiveDirectory module
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        Catch
        {

            Throw "Import-Module : Unable to import ActiveDirectory PowerShell Module. Run 'Install-WindowsFeature RSAT-AD-Tools' to install Active Directory RSAT."
        }
    }
}

# Encode reserved characters in DistinguishedName to Hexadecimal values based on MSDN documentation:
# The following table lists reserved characters that cannot be used in an attribute value without being escaped.
# From: https://msdn.microsoft.com/en-us/windows/desktop/aa366101
Function Convert-DNtoHex
{
    [CmdletBinding()]
    Param 
    (
        [Parameter(Mandatory=$True,Position=0)] [String] $DN
    )

    $encodedDN = $DN -replace '\\#','\23' `
                    -replace '\\,','\2C' `
                    -replace '\\"','\22' `
                    -replace '\\<','\3C' `
                    -replace '\\>','\3E' `
                    -replace '\\;','\3B' `
                    -replace '\\=','\3D' `
                    -replace '\\/','\2F'
    return $encodedDN
}

# Replace reserved characters for command line arguments
Function ReplaceReservedCharcters
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$True,Position=0)] [String] $PreReplace
    )    

    $postReplace = $PreReplace -replace '\"','\"'

    return $postReplace
}


# Export ADSyncConfig Module Functions
Export-ModuleMember -Function Set-ADSyncRestrictedPermissions
Export-ModuleMember -Function Set-ADSyncPasswordHashSyncPermissions
Export-ModuleMember -Function Set-ADSyncExchangeHybridPermissions
Export-ModuleMember -Function Set-ADSyncMsDsConsistencyGuidPermissions
Export-ModuleMember -Function Set-ADSyncPasswordWritebackPermissions
Export-ModuleMember -Function Set-ADSyncUnifiedGroupWritebackPermissions
Export-ModuleMember -Function Set-ADSyncExchangeMailPublicFolderPermissions
Export-ModuleMember -Function Set-ADSyncBasicReadPermissions
Export-ModuleMember -Function Get-ADSyncObjectsWithInheritanceDisabled
Export-ModuleMember -Function Get-ADSyncADConnectorAccount
Export-ModuleMember -Function Show-ADSyncADObjectPermissions

# SIG # Begin signature block
# MIInwgYJKoZIhvcNAQcCoIInszCCJ68CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC044O1QrO/mXzo
# vfAGyyj0C1vNPHfykaZ23vytrGQ046CCDY0wggYLMIID86ADAgECAhMzAAACXqZD
# 7dFf8ftHAAAAAAJeMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5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