Use-AzureAD.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
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154

#
## Created by: lucas.cueff[at]lucas-cueff.com
#
## released on 09/2021
#
# v0.5 - first public release - beta version - cmdlets to manage your Azure Active Directory Tenant (focusing on Administrative Unit features) when AzureADPreview cannot handle it correctly ;-)
# Note : currently Powershell Core and AzureADPreview are not working well together (logon / token request issue) : https://github.com/PowerShell/PowerShell/issues/10473 ==> this module will work only with Windows Powershell 5.1
# - cmdlet to get a valid access token (MFA supported) for Microsoft Graph Beta APIs
# - cmdlet to get a valid token for Microsoft Graph API standard / cloud endpoint (ressource graph.windows.net) and be able to use AzureADPreview cmdlets without reauthenticating
# - cmdlet to get all properties available (ex : extensionattribute) for an AAD user account
# - cmdlet to set a web proxy to be used with Use-AzureAD and AzureADPreview cmdlets
# - cmdlet to get all info for current logged in (@ Azure AD Tenant and Graph APIs) AAD user account
# - cmdlet to create / synchronize your on premise Active Directory OUs with Azure AD Administrive Units (not managed currently through Azure AD Connect or other Microsoft cmdlets / modules)
# - cmdlet to add / synchronize your on premise Active Directory users DN with Azure AD Administrative Unit membership (not managed currently through Azure AD Connect or other Microsoft cmdlets / modules)
# - cmdlet to add / remove Azure AD user account in Administrative Unit Role (everything managed in an easy and smooth way including, enabling the AAD role if missing and so on)
# - cmdlet to list all members of an Azure AD Administrative Unit (limited @ first 100 objets with default MS cmdlet... #WTF)
# v0.6 - beta version - focus on Azure AD Connect Cloud Provisionning Tools
# - cmdlet to get your current schema for a specific provisionning agent / service principal
# - cmdlet to update your current schema for a specific provisionning agent / service principal
# - cmdlet to get your default schema (template) for Azure AD Connect Cloud Provisionning
# - cmdlet to get a valid token (MFA supported) for Microsoft Graph API standard / cloud endpoint and MSOnline endpoint and be able to use MSOnline cmdlets without reauthenticating
# v0.7 - beta version - update Administrative Unit features (missing features from Microsoft Cmdlets and new API features)
# - cmdlet to create an Administrative Unit with hidden members
# - cmdlet to get Administrative Units with hidden members
# - cmdlet to create delta view for users, groups, admin units objects
# - cmdlet to get all updates from a delta view for users, groups, admin units objects
# v0.8 - beta version - fix azuread proxy bug when using SSO, add cmdlets to manage Azure AD Dynamic Security Groups
# - fix Set-AzureADproxy cmdlet : not able to set correctly the parameter *ProxyUseDefaultCredentials*
# - new cmdlets to add, get, update Azure AD Dynamic Membership security groups
# - cmdlet to test Dynamic membership for users
# Note : in current release of AzureADPreview I have found a bug regarding Dynamic group (all *-AzureADMSGroup cmdlets). When you try to use them, you have a Null Reference Exception :
# System.NullReferenceException,Microsoft.Open.MSGraphBeta.PowerShell.NewMSGroup
# v0.9 - beta version - add functions / cmdlets related to group and licensing stuff
# - cmdlet to get all Azure AD User with licensing error members of a particular group
# - cmdlet to get licensing info of a particular group
# - cmdlet to add or remove a license on an Azure AD Group
# - cmdlet to get licensing assignment type (group or user) of a particular user
# v1.0 - beta version - add service principal management for authentication and fix / improve code using DaveyRance remark : https://github.com/DaveyRance
# v1.1 - beta version - update authority URL for Service Principal to be compliant with last version of ADAL library
# v1.2 - beta version - add several functions to be able to manage OU to Admin unit sync in a service principal security context with delegated rights on API (must use MS Graph API only instead of mixing Azure AD Graph and MS Graph APIs) :
# - update Sync-ADOUtoAzureADAdministrativeUnit
# - update cmdlet Sync-ADUsertoAzureADAdministrativeUnitMember
# - update cmdlet Get-AzureADUserCustom (Get-AzureADUserallproperties)
# - add cmdlet Get-AzureADServicePrincipalCustom
# - add cmdlet Get-AzureADAdministrativeUnitCustom
# - add cmdlet Add-AzureADAdministrativeUnitMemberCustom
# - add cmdlet New-AzureADAdministrativeUnitCustom (New-AzureADAdministrativeUnitHidden)
# - add cmdlet Watch-AzureADAccessToken (be able to watch and auto renew Access Token of a service principal before expiration - useful in a script context when operation can take more than one hour)
# - update cmdlet Set-AzureADProxy (add bypassproxy on local option)
# v1.3 - beta version - add function to get administrative units of a user account and remove a user account from an administrative unit
# - Get-AzureADUserAdministrativeUnitMemberOfCustom
# - Remove-AzureADAdministrativeUnitMemberCustom
# v1.4 - beta version - add functions to get and update organization information
# - Get-AzureADOrganizationCustom
# - Update-AzureADOrganizationCustom
# v1.5.1 - beta version - add function to get Azure AD Connect synchronization errors through MS Graph API to replace Get-MsolDirSyncProvisioningError
# - Get-AzureADOnPremisesProvisionningErrors
# v1.6 - beta version - fix CallDepthOverflow on huge pages response
#
# v1.7 - last public version - beta version - add functions to create / update Office 365 groups with resourceBehaviorOptions and resourceProvisioningOptions : https://docs.microsoft.com/en-us/graph/group-set-options
# - New-AzureADMSGroupCustom
# - Set-AzureADMSGroupCustom
#
#'(c) 2021 lucas-cueff.com - Distributed under Artistic Licence 2.0 (https://opensource.org/licenses/artistic-license-2.0).'

<#
    .SYNOPSIS
    cmdlets to use several APIs of Microsoft Graph Beta web service (mainly users,me,AdministrativeUnit)
    extend AzureADPreview capabilities in Azure AD Administrative Unit management
 
    .DESCRIPTION
    use-AzureAD.psm1 module provides easy to use cmdlets to manage your Azure AD tenant with a focus on Administrative Unit objects.
     
    .EXAMPLE
    C:\PS> import-module use-AzureAD.psm1
#>

    Function Watch-AzureADAccessToken {
    <#
        .SYNOPSIS
        Follow an Azure Access Token requested for a service principal and auto renew it before expiration
     
        .DESCRIPTION
        Follow an Azure Access Token requested for a service principal and auto renew it before expiration
         
        .PARAMETER StartAutoRenewal
        -StartAutoRenewal switch
        Start autorenewal for an existing Azure AD Access Token (must be requested first with Get-AzureADAccessToken)
        limited use with service principal only for security purpose
         
        .PARAMETER StopAutoRenewal
        -StopAutoRenewal switch
        stop autorenewal for an existing Azure AD Access Token
         
        .OUTPUTS
           none
             
        .EXAMPLE
        Start to watch Azure AD Access Token requested for Service Principal 38846352-a67c-4a9a-a94c-c115be1fc52f and auto renew it before expiration
        C:\PS> Get-AzureADAccessToken -ServicePrincipalCertThumbprint E22EE5AE84909C49D4BF66C12BF88B2D0A53CDC2 -ServicePrincipalApplicationID 38846352-a67c-4a9a-a94c-c115be1fc52f -ServicePrincipalTenantDomain mydomain.tld
        C:\PS> Watch-AzureADAccessToken -StartAutoRenewal
         
        .EXAMPLE
        Stop autorenewal of Azure AD Access Token for Service Principal 38846352-a67c-4a9a-a94c-c115be1fc52f
        C:\PS> Watch-AzureADAccessToken -StopAutoRenewal
    #>

        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
                [switch]$StartAutoRenewal,
            [parameter(Mandatory=$false)]
                [switch]$StopAutoRenewal
        )
        process {
            if ($StartAutoRenewal.IsPresent) {
                Test-AzureADAccessTokenExpiration | out-null
                if (!($global:AADConnectInfo.ServicePrincipalName)) {
                    throw "please request an Access token with a Service Principal to use this function - exit"
                }
                if (!($global:AADConnectInfo.TokenWatch)) {
                    $global:AADRunSpaceTool = [hashtable]::Synchronized(@{})
                    $global:AADRunSpaceTool.add('Host',$Host)
                    if ($VerbosePreference) {
                        $global:AADRunSpaceTool.add('Verbose',$true)
                    }
                    $global:AADConnectInfo.add('TokenWatch',$true)
                    $global:AADRunspace = [runspacefactory]::CreateRunspace()
                    $global:AADRunspace.Open()
                    $global:AADRunspace.SessionStateProxy.SetVariable('AADConnectInfo',$AADConnectInfo)
                    $global:AADRunspace.SessionStateProxy.SetVariable('AADRunSpaceTool',$AADRunSpaceTool)
                    $global:AADPwsh = [powershell]::Create()
                    $global:AADPwsh.Runspace = $global:AADRunspace
                    $scriptblock = {
                        import-module Use-AzureAD -force
                        while ($AADConnectInfo.TokenWatch) {
                            if (Test-AzureADAccessTokenExpiration) {
                                if ($AADRunSpaceTool.verbose) {
                                    $AADRunSpaceTool.host.ui.WriteVerboseLine("expired token found")
                                }
                                if ($AADConnectInfo.ServicePrincipalName) {
                                    Clear-AzureADAccessToken -ServicePrincipalTenantDomain $AADConnectInfo.TenantName
                                    Get-AzureADAccessToken -ServicePrincipalCertThumbprint $AADConnectInfo.ServicePrincipalCertificate -ServicePrincipalApplicationID $AADConnectInfo.ServicePrincipalName -ServicePrincipalTenantDomain $AADConnectInfo.TenantName
                                    if ($AADRunSpaceTool.verbose) {
                                        $AADRunSpaceTool.host.ui.WriteVerboseLine($AADConnectInfo.AccessToken)
                                    }
                                }
                            }
                            start-sleep -Seconds 300
                            if ($AADRunSpaceTool.verbose) {
                                $AADRunSpaceTool.host.ui.WriteVerboseLine("token not expired")
                            }
                        } 
                    }
                    $global:AADPwsh.AddScript($scriptblock) | Out-Null
                    $global:AADTokenWatch = $global:AADPwsh.BeginInvoke()
                } else {
                    write-warning -Message "Azure AD Access token already monitored"
                }
            }
            if ($StopAutoRenewal.IsPresent) {
                if ($global:AADTokenWatch -and $global:AADConnectInfo.TokenWatch) {
                    $global:AADConnectInfo.TokenWatch = $false
                    $global:AADPwsh.EndInvoke($global:AADTokenWatch)
                    $global:AADRunspace.close()
                    $global:AADPwsh.Dispose()
                    $global:AADConnectInfo.remove('TokenWatch')
                    $global:AADConnectInfo.remove('host')
                    Remove-Variable -Name AADTokenWatch -Force -Scope Global
                    Remove-Variable -Name AADPwsh -Force -Scope Global
                    Remove-Variable -Name AADRunspace -Force -Scope Global
                    Remove-Variable -Name AADRunSpaceTool -Force -Scope Global
                }
            }
        }
    }
    Function Get-AzureADAccessToken {
    <#
        .SYNOPSIS
        Get a valid Access Token / Refresh Token for MS Graph APIs and MS Graph APIs Beta
     
        .DESCRIPTION
        Get a valid Access Token / Refresh Token for MS Graph APIs and MS Graph APIs Beta, using ADAL library, all authentication supported including MFA. Tenant ID automatically resolved.
         
        .PARAMETER adminUPN
        -adminUPN System.Net.Mail.MailAddress
        UserPrincipalName of an Azure AD account with rights on Directory (for instance a user with Global Admin right)
         
        .PARAMETER ServicePrincipalCertThumbprint
        -ServicePrincipalCertThumbprint string
        certificate thumbprint of the certificate to load (local machine certificate only)
         
        .PARAMETER ServicePrincipalApplicationID
        -ServicePrincipalApplicationID GUID
        guid of the application using the service principal
     
        .PARAMETER ServicePrincipalTenantDomain
        -ServicePrincipalTenantDomain string
        domain name / tenant name
     
        .OUTPUTS
           TypeName : System.Collections.Hashtable+SyncHashtable
             
        .EXAMPLE
        Get an access token for my admin account (my-admin@mydomain.tld)
        C:\PS> Get-AzureADAccessToken -adminUPN my-admin@mydomain.tld
         
        .EXAMPLE
        Get an access token for service principal with application ID 38846352-a67c-4a9a-a94c-c115be1fc52f and a certificate thumbprint of E22EE5AE84909C49D4BF66C12BF88B2D0A53CDC2
        C:\PS> Get-AzureADAccessToken -ServicePrincipalCertThumbprint E22EE5AE84909C49D4BF66C12BF88B2D0A53CDC2 -ServicePrincipalApplicationID 38846352-a67c-4a9a-a94c-c115be1fc52f -ServicePrincipalTenantDomain mydomain.tld
    #>

        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [System.Net.Mail.MailAddress]$adminUPN,
            [parameter(Mandatory=$false)]
            [ValidateScript({test-path "Cert:\LocalMachine\My\$_"})]
                [string]$ServicePrincipalCertThumbprint,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [guid]$ServicePrincipalApplicationID,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$ServicePrincipalTenantDomain
        )
        Process {
            if ($ServicePrincipalCertThumbprint -and (!($ServicePrincipalApplicationID) -or !($ServicePrincipalTenantDomain))) {
                throw "please use ServicePrincipalApplicationID with ServicePrincipalCertThumbprint and ServicePrincipalTenantDomain"
            }
            if ($ServicePrincipalApplicationID -and (!($ServicePrincipalCertThumbprint) -or !($ServicePrincipalTenantDomain))) {
                throw "please use ServicePrincipalApplicationID with ServicePrincipalCertThumbprint and ServicePrincipalTenantDomain"
            }
            $AadModule = Test-ADModule -AzureAD
            $adallib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
            [System.Reflection.Assembly]::LoadFrom($adallib) | Out-Null
            if ($adminUPN) {
                $clientId = "1b730954-1685-4b74-9bfd-dac224a7b894"
                $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
                $resourceURI = "https://graph.microsoft.com"
                $authority = "https://login.microsoftonline.com/$($adminUPN.Host)"
                try {
                    $adalformslib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
                    [System.Reflection.Assembly]::LoadFrom($adalformslib) | Out-Null
                    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
                    $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
                    $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($adminUPN.Address, "OptionalDisplayableId")
                    $authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientId, $redirectUri, $platformParameters, $userId)
                } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not able to log you on your Azure AD Tenant using user principal name provided - exiting"
                }
                if ($authResult.result) {
                    if (!($global:AADConnectInfo)) {
                        $global:AADConnectInfo = [hashtable]::Synchronized(@{})
                        $global:AADConnectInfo.add('UserName',$adminUPN)
                        $global:AADConnectInfo.add('AccessToken',$authResult.result.AccessToken)
                        $global:AADConnectInfo.add('TokenExpiresOn',$authResult.result.ExpiresOn)
                        $global:AADConnectInfo.add('ObjectID',(Get-AzureADMyInfo).id)
                        $global:AADConnectInfo.add('TenantID',(Get-AzureADTenantInfo -adminUPN $adminUPN).TenantID)
                        $global:AADConnectInfo.add('TenantName',$adminUPN.Host)
                    } else {
                        $global:AADConnectInfo.UserName = $adminUPN
                        $global:AADConnectInfo.AccessToken = $authResult.result.AccessToken
                        $global:AADConnectInfo.TokenExpiresOn = $authResult.result.ExpiresOn
                        $global:AADConnectInfo.ObjectID = (Get-AzureADMyInfo).id
                        $global:AADConnectInfo.TenantID = (Get-AzureADTenantInfo -adminUPN $adminUPN).TenantID
                        $global:AADConnectInfo.TenantName = $adminUPN.Host
                        if ($global:AADConnectInfo.ServicePrincipalCertificate) {
                            $global:AADConnectInfo.remove('ServicePrincipalCertificate')
                        }
                        if ($global:AADConnectInfo.ServicePrincipalName) {
                            $global:AADConnectInfo.remove('ServicePrincipalName')
                        }
                    }
                } else {
                    $authResult
                    throw "Authorization Access Token is null, please re-run authentication - exiting"
                }
            }
            if ($ServicePrincipalCertThumbprint -and $ServicePrincipalApplicationID -and $ServicePrincipalTenantDomain) {
                $CertStore = "Cert:\LocalMachine\My"
                $CertStorePath = Join-Path $CertStore $ServicePrincipalCertThumbprint
                $Certificate = Get-Item $CertStorePath
                if (!$Certificate) {
                  throw "not able to get certificate with $ServicePrincipalCertThumbprint thumbprint in local machine cert store - exiting"
                }
                $tenantinfo = Get-AzureADTenantInfo -ServicePrincipalTenantDomain $ServicePrincipalTenantDomain
                $resourceURI = "https://graph.microsoft.com"
                $authority = "https://login.microsoftonline.com/$($tenantinfo.TenantID)"
                try {
                    $ClientCert = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate" -ArgumentList ($ServicePrincipalApplicationID.guid, $Certificate)
                    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
                    $authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientCert)
                } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not able to log you on your Azure AD Tenant using Service Principal information provided - exiting"
                }
                if ($authResult.result) {
                    if (!($global:AADConnectInfo)) {
                        $global:AADConnectInfo = [hashtable]::Synchronized(@{})
                        $global:AADConnectInfo.add('ServicePrincipalName',$ServicePrincipalApplicationID)
                        $global:AADConnectInfo.add('ServicePrincipalCertificate',$ServicePrincipalCertThumbprint)
                        $global:AADConnectInfo.add('AccessToken',$authResult.result.AccessToken)
                        $global:AADConnectInfo.add('TokenExpiresOn',$authResult.result.ExpiresOn)
                        $global:AADConnectInfo.add('ObjectID',(Get-AzureADServicePrincipalCustom -Filter "appid eq '$($ServicePrincipalApplicationID)'").id)
                        $global:AADConnectInfo.add('TenantID',$tenantinfo.TenantID)
                        $global:AADConnectInfo.add('TenantName',$ServicePrincipalTenantDomain)
                    } else {
                        $global:AADConnectInfo.ServicePrincipalName = $ServicePrincipalApplicationID
                        $global:AADConnectInfo.ServicePrincipalCertificate = $ServicePrincipalCertThumbprint
                        $global:AADConnectInfo.AccessToken = $authResult.result.AccessToken
                        $global:AADConnectInfo.TokenExpiresOn = $authResult.result.ExpiresOn
                        $global:AADConnectInfo.ObjectID = (Get-AzureADServicePrincipalCustom -Filter "appid eq '$($ServicePrincipalApplicationID)'").id
                        $global:AADConnectInfo.TenantID = $tenantinfo.TenantID
                        $global:AADConnectInfo.TenantName = $ServicePrincipalTenantDomain
                        if ($global:AADConnectInfo.UserName) {
                            $global:AADConnectInfo.remove('UserName')
                        }
                    }
                } else {
                    $authResult
                    throw "Authorization Access Token is null, please re-run authentication - exiting"
                }
            }
            $global:AADConnectInfo
        }
    }
    Function Get-AzureADMyInfo {
    <#
        .SYNOPSIS
        Get all Azure AD account properties of current logged in user
     
        .DESCRIPTION
        Get all Azure AD account properties of current logged in user. Note : including hidden properties like extensionattribute.
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get all user account properties of my current account (my-admin@mydomain.tld)
        C:\PS> Get-AzureADMyInfo
    #>

        [cmdletbinding()]
        Param ()
        process {
            Test-AzureADAccessTokenExpiration | out-null
            Invoke-APIMSGraphBeta -API "me" -Method "GET"
        }
    }
    Function Get-AzureADTenantInfo {
    <#
        .SYNOPSIS
        Get a valid Access Tokem / Refresh Token for MS Graph APIs and MS Graph APIs Beta
     
        .DESCRIPTION
        Get a valid Access Tokem / Refresh Token for MS Graph APIs and MS Graph APIs Beta, using ADAL library, all authentication supported including MFA. Tenant ID automatically resolved.
         
        .PARAMETER adminUPN
        -adminUPN System.Net.Mail.MailAddress
        UserPrincipalName of an Azure AD account with rights on Directory (for instance a user with Global Admin right)
         
        .PARAMETER ServicePrincipalTenantDomain
        -ServicePrincipalTenantDomain string
        Tenant domain name of your Service Principal account
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get tenant info from my useraccount (my-admin@mydomain.tld)
        C:\PS> Get-AzureADTenantInfo -adminUPN my-admin@mydomain.tld
         
        .EXAMPLE
        Get tenant info from my service principal tenant domain name (mydomain.tld)
        C:\PS> Get-AzureADTenantInfo -ServicePrincipalTenantDomain mydomain.tld
    #>

        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [System.Net.Mail.MailAddress]$adminUPN,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$ServicePrincipalTenantDomain
        )
        process {
            if ($adminUPN) {
                $url = "https://login.microsoftonline.com/$($adminUPN.Host)/.well-known/openid-configuration"
                write-verbose -Message "GET method to $($url)"
            }
            if ($ServicePrincipalTenantDomain) {
                $url = "https://login.microsoftonline.com/$($ServicePrincipalTenantDomain)/.well-known/openid-configuration"
                write-verbose -Message "GET method to $($url)"
            }
            Try {
                $tmpobj = (Invoke-WebRequest $url).content | ConvertFrom-Json
            } catch {
                $tmpobj = $_ | ConvertFrom-Json
            }
            if ($tmpobj.issuer) {
                $tmpobj | Add-Member -MemberType NoteProperty -Name 'TenantID' -Value ([uri]$tmpobj.issuer).AbsolutePath.Replace("/","")
            }
            $tmpobj
        }
    }
    Function Connect-AzureADFromAccessToken {
    <#
        .SYNOPSIS
        Connect to your Azure AD Tenant / classic MS Graph endpoint used by AzureADPreview module using an existing Access token requested with Get-AzureADAccessToken
     
        .DESCRIPTION
        Connect to your Azure AD Tenant / classic MS Graph endpoint used by AzureADPreview module using an existing Access token requested with Get-AzureADAccessToken
                 
        .OUTPUTS
           TypeName : Microsoft.Open.Azure.AD.CommonLibrary.PSAzureContext
             
        .EXAMPLE
        Connect to your Azure AD Tenant / classic MS Graph endpoint used by AzureADPreview module using an existing Access token requested with Get-AzureADAccessToken
        C:\PS> Connect-AzureADFromAccessToken
    #>

        [cmdletbinding()]
        Param ()
        Test-AzureADAccessTokenExpiration | out-null
        $AadModule = Test-ADModule -AzureAD
        if ($global:AADConnectInfo.AccessToken) {
            if ($global:AADConnectInfo.UserName) {
                $resourceURI = "https://graph.windows.net"
                $clientId = "1b730954-1685-4b74-9bfd-dac224a7b894"
                $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
                $authority = "https://login.microsoftonline.com/$(($global:AADConnectInfo.UserName).host)"
                try {
                    $adallib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
                    $adalformslib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
                    [System.Reflection.Assembly]::LoadFrom($adallib) | Out-Null
                    [System.Reflection.Assembly]::LoadFrom($adalformslib) | Out-Null
                    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
                    $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
                    $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($global:AADConnectInfo.UserName, "OptionalDisplayableId")
                    $authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientId, $redirectUri, $platformParameters, $userId)
                } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not Able to log you on your Azure AD Tenant - exiting"
                }        
                connect-azuread -tenantid $global:AADConnectInfo.TenantID -AadAccessToken $authResult.result.AccessToken -MsAccessToken $global:AADConnectInfo.AccessToken -AccountId $global:AADConnectInfo.ObjectID
            }
            if ($global:AADConnectInfo.ServicePrincipalName) {
                $CertStore = "Cert:\LocalMachine\My"
                $CertStorePath = Join-Path $CertStore $global:AADConnectInfo.ServicePrincipalCertificate
                $Certificate = Get-Item $CertStorePath
                if (!$Certificate) {
                    throw "not able to get certificate with $ServicePrincipalCertThumbprint thumbprint in local machine cert store - exiting"
                }
                connect-azuread -tenantid $global:AADConnectInfo.TenantID -ApplicationId $global:AADConnectInfo.ServicePrincipalName -CertificateThumbprint $global:AADConnectInfo.ServicePrincipalCertificate
            }
        } else {
            throw "No valid Access Token found - exiting"
        }
    }
    Function Connect-MSOnlineFromAccessToken {
        <#
            .SYNOPSIS
            Connect to your Azure AD Tenant / classic MS Graph endpoint used by MSOnline module using an existing Access token requested with Get-AzureADAccessToken
         
            .DESCRIPTION
            Connect to your Azure AD Tenant / classic MS Graph endpoint used by MSOnline module using an existing Access token requested with Get-AzureADAccessToken
                     
            .OUTPUTS
            None
                     
            .EXAMPLE
            Connect to your Azure AD Tenant / classic MS Graph endpoint used by MSOnline module using an existing Access token requested with Get-AzureADAccessToken
            C:\PS> Connect-MSOnlineFromAccessToken
        #>

            [cmdletbinding()]
            Param ()
            Test-AzureADAccessTokenExpiration | out-null
            Test-ADModule -MSOnline | out-null
            $AadModule = Test-ADModule -AzureAD
            if ($global:AADConnectInfo.AccessToken) {
                if ($global:AADConnectInfo.UserName) {
                    $resourceURI = "https://graph.windows.net"
                    $clientId = "1b730954-1685-4b74-9bfd-dac224a7b894"
                    $redirectUri = new-object System.Uri("http://localhost/")
                    $authority = "https://login.microsoftonline.com/$(($global:AADConnectInfo.UserName).host)"
                    try {
                        $adallib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
                        $adalformslib = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
                        [System.Reflection.Assembly]::LoadFrom($adallib) | Out-Null
                        [System.Reflection.Assembly]::LoadFrom($adalformslib) | Out-Null
                        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
                        $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
                        $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($global:AADConnectInfo.UserName, "OptionalDisplayableId")
                        $authResult = $authContext.AcquireTokenAsync($resourceURI, $ClientId, $redirectUri, $platformParameters, $userId)
                    } catch {
                        Write-Error -Message "$($_.Exception.Message)"
                        throw "Not Able to log you on your Azure AD Tenant - exiting"
                    }
                    Connect-MsolService -AccessToken $authResult.result.AccessToken
                }
                if ($global:AADConnectInfo.ServicePrincipalName) {
                    Write-Warning -message "Service Principals are not supported for passthrough token to MSOnline."
                }
            } else {
                throw "No valid Access Token found - exiting"
            }
    }
    Function Set-AzureADProxy {
    <#
        .SYNOPSIS
        Set a web proxy to connect to Azure AD graph API
     
        .DESCRIPTION
        Set / remove a proxy to connect to your Azure AD environment using AzureADPreview module or this module. Can handle anonymous proxy or authenticating proxy.
         
        .PARAMETER DirectNoProxy
        -DirectNoProxy Swith
        Remove proxy set, set to "direct" connection
         
        .PARAMETER Proxy
        -Proxy uri
        Set the proxy settings to URI provided. Must be provided as a valid URI like http://proxy:port
         
        .PARAMETER ProxyCredential
        -ProxyCredential Management.Automation.PSCredential
        must be use with Proxy parameter
        Set the credential to be used with the proxy to set. Must be provided as a valid PSCredential object (can be generated with Get-Credential)
     
        .PARAMETER ProxyUseDefaultCredentials
        -ProxyUseDefaultCredentials Swith
        must be use with Proxy parameter
        Set the credential to be used with the proxy to set. this switch will tell the system to use the current logged in credential to be authenticated with the proxy service.
             
        .OUTPUTS
           TypeName : System.Net.WebProxy
             
        .EXAMPLE
        Remove Proxy
        C:\PS> Set-AzureADProxy -DirectNoProxy
         
        .EXAMPLE
        Set a local anonymous proxy 127.0.0.1:8888
        C:\PS> Set-AzureADProxy -Proxy "http://127.0.0.1:8888"
         
        .EXAMPLE
        Set a local anonymous proxy 127.0.0.1:8888 and request local traffic to not be sent to proxy
        C:\PS> Set-AzureADProxy -Proxy "http://127.0.0.1:8888" -BypassProxyOnLocal
    #>

        [cmdletbinding()]
        Param (
          [Parameter(Mandatory=$false)]
            [switch]$DirectNoProxy,
          [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
            [uri]$Proxy,
          [Parameter(Mandatory=$false)]
            [Management.Automation.PSCredential]$ProxyCredential,
          [Parameter(Mandatory=$false)]
            [Switch]$ProxyUseDefaultCredentials,
          [Parameter(Mandatory=$false)]
            [switch]$BypassProxyOnLocal
        )
        process {
            if ($DirectNoProxy.IsPresent){
                [System.Net.WebRequest]::DefaultWebProxy = $null
            } ElseIf ($Proxy) {
                $proxyobj = New-Object System.Net.WebProxy $proxy.AbsoluteUri            
                if ($ProxyCredential){
                    $proxyobj.Credentials = $ProxyCredential
                } Elseif ($ProxyUseDefaultCredentials.IsPresent){
                    $proxyobj.UseDefaultCredentials = $true
                }
                if ($BypassProxyOnLocal.IsPresent) {
                    $proxyobj.BypassProxyOnLocal = $true
                }
                [System.Net.WebRequest]::DefaultWebProxy = $proxyobj
                $proxyobj
            }
        }
    }
    Function Clear-AzureADAccessToken {
    <#
        .SYNOPSIS
        Clear an existing MS Graph APIs and MS Graph APIs Beta Access Token
     
        .DESCRIPTION
        Clear an existing MS Graph APIs and MS Graph APIs Beta Access Token. Required to be already authenticated.
         
        .PARAMETER adminUPN
        -adminUPN System.Net.Mail.MailAddress
        UserPrincipalName of the Azure AD account currently logged in that you want the access token to be removed
         
        .PARAMETER ServicePrincipalTenantDomain
        -ServicePrincipalTenantDomain string
        domain name / tenant name
             
        .OUTPUTS
        None
             
        .EXAMPLE
        clear an access token for my admin account (my-admin@mydomain.tld)
        C:\PS> Clear-AzureADAccessToken -adminUPN my-admin@mydomain.tld
     
        .EXAMPLE
        clear an access token for a service principal from mydomain.tld
        C:\PS> Clear-AzureADAccessToken -ServicePrincipalTenantDomain mydomain.tld
    #>

        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [System.Net.Mail.MailAddress]$adminUPN,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$ServicePrincipalTenantDomain
        )
        if ($adminUPN) {
            $authority = "https://login.microsoftonline.com/$($adminUPN.Host)"
        }
        if ($ServicePrincipalTenantDomain) {
            $authority = "https://login.microsoftonline.com/$($ServicePrincipalTenantDomain)"
        }
        if (!($adminUPN) -and !($ServicePrincipalTenantDomain)) {
            throw "please use ServicePrincipalTenantDomain or adminUPN parameter"
        }
        Test-ADModule -AzureAD | Out-Null
        try {
            $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
            $authContext.TokenCache.Clear()
        } catch {
            throw "Not Able to clear your current tokens and disconnect your session - exiting"
        }
    }
    Function Sync-ADOUtoAzureADAdministrativeUnit {
    <#
        .SYNOPSIS
        Create new Azure AD Administrative Unit based on on premise AD Organizational Unit
     
        .DESCRIPTION
        Create new Azure AD Administrative Unit based on on premise AD Organizational Unit. Can be used to synchronize all existing on prem AD root OU with new cloud Admin unit.
         
        .PARAMETER AllOUs
        -AllOUs Switch
        Synchronize all existing OU to new cloud Admin Unit (except default OU like Domain Controllers)
         
        .PARAMETER OUsFilterName
        -OUsFilterName string
        must be used with AllOUs parameter
        Set a regex filter to synchronize only OU based on a specific pattern.
     
        .PARAMETER SearchBase
        -SearchBase string
        must be used with AllOUs parameter
        set the default search base for OU (DN format)
     
        .PARAMETER OUsDN
        -OUsDN string / array of string
        must not be used with AllOUs parameter. you must choose between these 2 parameters.
        string must be a LDAP Distinguished Name. For instance : "OU=TP-VB,DC=domain,DC=xyz"
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Create new cloud Azure AD administrative Unit for each on prem' OU found with a pattern like "AB-CD"
        The verbose option can be used to write basic message on console (for instance when an admin unit already existing)
        C:\PS> Sync-ADOUtoAzureADAdministrativeUnit -AllOUs -OUsFilterName "^([a-zA-Z]{2})(-)([a-zA-Z]{2})$" -SearchBase "DC=domain,DC=xyz" -Verbose
    #>

    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$false)]
            [switch]$AllOUs,
        [parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
            [string]$OUsFilterName,
        [parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
            [string[]]$OUsDN,
        [parameter(Mandatory=$false)]
            [string]$SearchBase
    )
    process {
        if (!($AllOUs.IsPresent) -and !($OUsDN)) {
            throw "AllOUs switch parameter or OUsDN parameter must be used - exiting"
        }
        if ($AllOUs.IsPresent -and !($SearchBase)) {
            throw "SearchBase parameter must be used with AllOUs switch - exiting"
        }
        Test-ADModule -AD | Out-Null
        Test-AzureADAccessTokenExpiration | out-null
        If ($AllOUs.IsPresent) {
            if ($OUsFilterName) {
                $OUs = Get-ADOrganizationalUnit -Filter * -SearchBase $SearchBase
                $OUs = $OUs | where-object {$_.Name -match $OUsFilterName}
            } else {
                $Ous = Get-ADOrganizationalUnit -Filter {name -ne "Domain Controllers"} -SearchBase $SearchBase
            }
        } elseif ($OUsDN) {
            $OUs = @()
            foreach ($OU in $OUsDN) {
                if ($OU -match "^(?:(?<cn>CN=(?<name>[^,]*)),)?(?:(?<path>(?:(?:CN|OU)=[^,]+,?)+),)?(?<domain>(?:DC=[^,]+,?)+)$") {
                    try {
                        $OU = Get-ADOrganizationalUnit -Identity $OU
                    } Catch {
                        write-verbose -message "OU $($OU) not found in directory"
                    }
                    if ($OU) {
                        $OUs += $OU
                    }
                }
            }
        }
        foreach ($OU in $OUs) {
            If (!(Get-AzureADAdministrativeUnitCustom -Filter "displayname eq '$($OU.name)'").id) {
                try {
                    New-AzureADAdministrativeUnitCustom -Description "Windows Server AD OU $($OU.DistinguishedName)" -DisplayName $OU.name
                } catch {
                    write-error -message $_.Exception.Message
                }
                write-verbose -message "$($OU.name) Azure Administrative Unit created"
            } else {
                write-verbose -message  "$($OU.name) Azure Administrative Unit already exists"
            }
        }
            Get-AzureADAdministrativeUnitCustom -All
        }
    }
    Function Sync-ADUsertoAzureADAdministrativeUnitMember {
    <#
        .SYNOPSIS
        Add Azure AD user account into Azure AD Administrative Unit based on their on premise LDAP Distinguished Name
     
        .DESCRIPTION
        Add Azure AD user account into Azure AD Administrative Unit based on their on premise LDAP Distinguished Name.
         
        .PARAMETER CloudUPNAttribute
        -CloudUPNAttribute string
        On premise AD user account attribute hosting the cloud Azure AD User userprincipal name. For instance, it could be also the userPrincipalName attribute or mail attribute.
         
        .PARAMETER AllOUs
        -AllOUs Switch
        Synchronize all existing OU to new cloud Admin Unit (except default OU like Domain Controllers)
         
        .PARAMETER OUsFilterName
        -OUsFilterName string
        must be used with AllOUs parameter
        Set a regex filter to synchronize only OU based on a specific pattern.
     
        .PARAMETER SearchBase
        -SearchBase string
        must be used with AllOUs parameter
        set the default search base for OU (DN format)
     
        .PARAMETER OUsDN
        -OUsDN string / array of string
        must not be used with AllOUs parameter. you must choose between these 2 parameters.
        string must be a LDAP Distinguished Name. For instance : "OU=TP-VB,DC=domain,DC=xyz"
             
        .OUTPUTS
           None. verbose can be used to display message on console.
             
        .EXAMPLE
        Add Azure AD users to administrative unit based on their source Distinguished Name, do it only for users account with a DN containing a root OU name matching a pattern like "AB-CD"
        The verbose option can be used to write basic message on console (for instance when a user is already member of an admin unit)
        C:\PS> Sync-ADUsertoAzureADAdministrativeUnitMember -CloudUPNAttribute mail -AllOUs -OUsFilterName "^([a-zA-Z]{2})(-)([a-zA-Z]{2})$" -SearchBase "DC=domain,DC=xyz" -Verbose
    #>

    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
            [string]$CloudUPNAttribute,
        [parameter(Mandatory=$false)]
            [switch]$AllOUs,
        [parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
            [string]$OUsFilterName,
        [parameter(Mandatory=$false)]
            [string]$SearchBase,
        [parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
            [string[]]$OUsDN,
        [parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
            [string]$ADUserFilter
    )
    process {
        if (!($AllOUs.IsPresent) -and !($OUsDN)) {
            throw "AllOUs switch parameter or OUsDN parameter must be used - exiting"
        }
        if ($AllOUs.IsPresent -and !($SearchBase)) {
            throw "SearchBase parameter must be used with AllOUs switch - exiting"
        }
        if (!($ADUserFilter)) {
            $ADUserFilter = "*"
        }
        Test-ADModule -AD | Out-Null
        Test-AzureADAccessTokenExpiration | out-null
        If ($AllOUs.IsPresent) {
            if ($OUsFilterName) {
                $OUs = Get-ADOrganizationalUnit -Filter * -SearchScope OneLevel -SearchBase $SearchBase
                $OUs = $OUs | where-object {$_.Name -match $OUsFilterName}
            } else {
                $Ous = Get-ADOrganizationalUnit -Filter {name -ne "Domain Controllers"} -SearchBase $SearchBase
            }
        } elseif ($OUsDN) {
            $OUs = @()
            foreach ($OU in $OUsDN) {
                if ($OU -match "^(?:(?<cn>CN=(?<name>[^,]*)),)?(?:(?<path>(?:(?:CN|OU)=[^,]+,?)+),)?(?<domain>(?:DC=[^,]+,?)+)$") {
                    try {
                        $OU = Get-ADOrganizationalUnit -Identity $OU
                    } Catch {
                        write-error -message "OU $($OU) not found in directory"
                    }
                    if ($OU) {
                        write-verbose -message "OU $($OU) found in directory"
                        $OUs += $OU
                    }
                }
            }
        }
        foreach ($OU in $OUs) {
            $AZADMUnit = Get-AzureADAdministrativeUnitCustom -Filter "displayname eq '$($OU.name)'"
            If ($AZADMUnit.id) {
                $AZADMUnitMember = Get-AzureADAdministrativeUnitAllMembers -objectid $AZADMUnit.ID
                $users = Get-ADUser -SearchBase $OU.DistinguishedName -SearchScope Subtree -Filter $ADUserFilter -Properties $CloudUPNAttribute
                foreach ($user in $users) {
                    $azureaduser = Get-AzureADUserCustom -userUPN $user.$CloudUPNAttribute
                    if ($azureaduser.error) {
                        write-verbose -message"Azure AD User $($user.$CloudUPNAttribute) not found"
                    } else {
                        if ($user.($CloudUPNAttribute)) {
                            write-verbose -message "Azure AD User $($user.$CloudUPNAttribute) found"
                            if ($AZADMUnitMember) {
                                if ($AZADMUnitMember.ID -contains $azureaduser.ID) {
                                    write-verbose -message "Azure AD User $($user.($CloudUPNAttribute)) already member of $($OU.name) Azure Administrative Unit"
                                } else {
                                    write-verbose -message "Azure AD User $($user.($CloudUPNAttribute)) not member of $($OU.name) Azure Administrative Unit"
                                    try {
                                        Add-AzureADAdministrativeUnitMemberCustom -ObjectId $AZADMUnit.ID -RefObjectId $azureaduser.ID -RefObjectType users
                                    } catch {
                                        write-error -message $_.Exception.Message
                                        write-error -message "not able to add $($user.($CloudUPNAttribute)) Azure AD User in $($OU.name) Azure Administrative Unit"
                                    }
                                    write-verbose -message "Azure AD User $($user.($CloudUPNAttribute)) added in $($OU.name) Azure Administrative Unit"
                                }
                            } else {
                                write-verbose -message "Azure AD User $($user.($CloudUPNAttribute)) not member of $($OU.name) Azure Administrative Unit"
                                try {
                                    Add-AzureADAdministrativeUnitMemberCustom -ObjectId $AZADMUnit.ID -RefObjectId $azureaduser.ID -RefObjectType users
                                } catch {
                                    write-error -message $_.Exception.Message
                                    write-error -message "not able to add $($user.($CloudUPNAttribute)) Azure AD User in $($OU.name) Azure Administrative Unit"
                                }
                                write-verbose -message "Azure AD User $($user.($CloudUPNAttribute)) added in $($OU.name) Azure Administrative Unit"
                            }
                        }
                    }
                }
            }
        }
    }
    }
    Function Set-AzureADAdministrativeUnitAdminRole {
    <#
        .SYNOPSIS
        Add / remove Azure AD administrative unit role to Azure AD user
     
        .DESCRIPTION
        Add / remove Azure AD administrative unit role to Azure AD user
         
        .PARAMETER AdministrativeUnit
        -AdministrativeUnit string
        Dynamic parameter built using the list of Administrative Unit created in your Tenant.
         
        .PARAMETER AdministrativeRole
        -AdministrativeRole string
        Dynamic parameter built using the list of Role template available in your Tenant.
        Note : warning, currently all roles are not compliant with Administrative Unit object.
     
        .PARAMETER userUPN
        -userUPN System.Net.Mail.MailAddress
        user principal name of the account you want to add a new role
     
        .PARAMETER RoleAction
        -RoleAction string {Add, Remove}
        Specify the action to be done with the target role on the Azure AD user object : add or remove the role
             
        .OUTPUTS
           TypeName : Microsoft.Open.AzureAD.Model.ScopedRoleMembership
             
        .EXAMPLE
        Give the role Password Administrator for the Admin unit TP-NF to my-admin-unit@mydomain.tld
        C:\PS> Set-AzureADAdministrativeUnitAdminRole -userUPN my-admin-unit@mydomain.tld -RoleAction ADD -AdministrativeUnit TP-NF -AdministrativeRole 'Password Administrator' -Verbose
    #>

        [cmdletbinding()]
        param (
            [parameter(Mandatory=$true,Position=2)]
            [ValidateNotNullOrEmpty()]
                [System.Net.Mail.MailAddress]$userUPN,
            [parameter(Mandatory=$true,position=4)]
            [validateSet("Add","Remove")]
                [string]$RoleAction
        )
        DynamicParam
        {
            $ParameterNameAdmUnit = 'AdministrativeUnit'
            $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
            $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
            $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute.ValueFromPipeline = $false
            $ParameterAttribute.ValueFromPipelineByPropertyName = $false
            $ParameterAttribute.Mandatory = $true
            $ParameterAttribute.Position = 1
            $AttributeCollection.Add($ParameterAttribute)
            $arrSet = (Get-AzureADAdministrativeUnit).displayname
            $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
            $AttributeCollection.Add($ValidateSetAttribute)
            $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterNameAdmUnit, [string], $AttributeCollection)
            $RuntimeParameterDictionary.Add($ParameterNameAdmUnit, $RuntimeParameter)
            
            $ParameterNameAdmRole = 'AdministrativeRole'
            $AttributeCollection2 = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
            $ParameterAttribute2 = New-Object System.Management.Automation.ParameterAttribute
            $ParameterAttribute2.ValueFromPipeline = $false
            $ParameterAttribute2.ValueFromPipelineByPropertyName = $false
            $ParameterAttribute2.Mandatory = $true
            $ParameterAttribute2.Position = 3
            $AttributeCollection2.Add($ParameterAttribute2)
            $arrSet =  (Get-AzureADDirectoryRoleTemplate).displayname
            $ValidateSetAttribute2 = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
            $AttributeCollection2.Add($ValidateSetAttribute2)
            $RuntimeParameter2 = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterNameAdmRole, [string], $AttributeCollection2)
            $RuntimeParameterDictionary.Add($ParameterNameAdmRole, $RuntimeParameter2)
            
            return $RuntimeParameterDictionary
       }
        Process {
           $AdminUnit = $PsBoundParameters[$ParameterNameAdmUnit]
           $AdminRole = $PsBoundParameters[$ParameterNameAdmRole]
           Test-ADModule -AzureAD | out-null
           Test-AzureADAccessTokenExpiration | out-null
           try {
               $UserObj = Get-AzureADUser -ObjectId $userUPN.Address
           } catch {
                Write-Error -Message "$($_.Exception.Message)"
                throw "Not able to find user $($userUPN.Address) - exiting"  
           }
           $AdminUnitObj = Get-AzureADAdministrativeUnit -filter "DisplayName eq '$($AdminUnit)'"
           if (!($AdminUnitObj)) {
               throw "Not able to find $($AdminUnit) Azure AD Administrative Unit - exiting"
           }
           $AdminroleObj = Get-AzureADDirectoryRole -Filter "DisplayName eq '$($AdminRole)'"
           if (!($AdminroleObj)) {
               write-verbose -message "$($AdminRole) role currently disabled, needed to enable it before adding member"
                try {
                    $AdminroleObj = Enable-AzureADDirectoryRole -RoleTemplateId (Get-AzureADDirectoryRoleTemplate | Where-Object {$_.Displayname -eq $AdminRole}).ObjectId
                } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not able to enable requested role $($AdminRole) - exiting"
                }
           }
           try { 
               $AdminRoleMember = (Get-AzureADScopedRoleMembership -ObjectId $AdminUnitObj.ObjectID | Where-Object {$_.RoleObjectID -eq $AdminroleObj.ObjectID}).RoleMemberInfo
           } catch {
                Write-Error -Message "$($_.Exception.Message)"
           }
           If (($AdminRoleMember.ObjectId -contains $UserObj.ObjectId) -and ($RoleAction -eq "ADD")) {
               write-verbose "User $($userUPN.Address) already member of $($AdminRole) role"
           } elseif (($AdminRoleMember.ObjectId -notcontains $UserObj.ObjectId) -and ($RoleAction -eq "ADD")) {
               try {
                    $AdmRoleMemberInfo = New-Object -TypeName Microsoft.Open.AzureAD.Model.RoleMemberInfo -Property @{ ObjectId =  $UserObj.ObjectId }
                    Add-AzureADScopedRoleMembership -RoleObjectId $AdminroleObj.ObjectID -ObjectId $AdminUnitObj.ObjectID -RoleMemberInfo $AdmRoleMemberInfo
               } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not able to add $($userUPN.Address) user in $($AdminRole) role for $($AdminUnit) Azure administrative unit - exiting"
               }
           }
           If (($AdminRoleMember.ObjectId -notcontains $UserObj.ObjectId) -and ($RoleAction -eq "Remove")) {
            write-verbose "User $($userUPN.Address) already removed from $($AdminRole) role"
            } elseif (($AdminRoleMember.ObjectId -contains $UserObj.ObjectId) -and ($RoleAction -eq "Remove")) {
                try {
                    $AdmRoleMembershipID = (Get-AzureADScopedRoleMembership -ObjectId $AdminUnitObj.ObjectID | Where-Object {($_.RoleObjectID -eq $AdminroleObj.ObjectID) -and ($_.RoleMemberInfo.ObjectId -eq $UserObj.ObjectID)}).ID
                    Remove-AzureADScopedRoleMembership -ObjectId $AdminUnitObj.ObjectID -ScopedRoleMembershipId $AdmRoleMembershipID
                } catch {
                    Write-Error -Message "$($_.Exception.Message)"
                    throw "Not able to remove $($userUPN.Address) user from $($AdminRole) role for $($AdminUnit) Azure administrative unit - exiting"
                }
            }
            Get-AzureADScopedRoleMembership -ObjectId $AdminUnitObj.ObjectID
       }
    }
    Function Get-AzureADUserCustom {
    <#
        .SYNOPSIS
        Get all info available for an existing Azure AD account
     
        .DESCRIPTION
        Get all info available for an existing Azure AD account (all user properties available including all the hidden one not managed by Get-AzureADUsers)
         
        .PARAMETER userUPN
        -userUPN System.Net.Mail.MailAddress
        UserPrincipalName of an Azure AD account
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.User
         Microsoft.Open.AzureAD.Model.User object (for instance generated by Get-AzureADUser)
     
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Azure AD user object
     
        .PARAMETER Filter
        -Filter string
        Odata Filter query
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get all users properties available for the Azure AD account my-admin@mydomain.tld
        C:\PS> get-azureaduser -ObjectId "my-admin@mydomain.tld" | Get-AzureADUserCustom
     
        .EXAMPLE
        Get all users properties available for the Azure AD account my-admin@mydomain.tld
        C:\PS> Get-AzureADUserCustom -userUPN "my-admin@mydomain.tld"
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.User]$inputobject,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [System.Net.Mail.MailAddress]$userUPN,
            [parameter(Mandatory=$false)]
                [switch]$All,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$Filter,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [guid]$ObjectId
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($userUPN) -and !($inputobject) -and !($all.IsPresent) -and !($ObjectId) -and ($Filter)) {
                throw "Please use userUPN or inputobject or Filter or ObjectID Parameter or All switch - exiting"
            }
            $params = @{
                API = "users"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $params.add('APIParameter',$inputobject.ObjectId)
            } elseif ($userUPN.Address) {
                $params.add('APIParameter',$userUPN.Address)
            } elseif ($ObjectId) {
                $params.add('APIParameter',$ObjectId.Guid)
            } elseif ($Filter) {
                $params.add('APIParameter',"?`$filter=$($Filter)")
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADAdministrativeUnitAllMembers {
    <#
        .SYNOPSIS
        Get all Azure AD account member of an Azure AD Administrative Unit
     
        .DESCRIPTION
        Get all Azure AD account member of an Azure AD Administrative Unit
         
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Administrative Unit
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.AdministrativeUnit
        Microsoft.Open.AzureAD.Model.AdministrativeUnit object (for instance created by Get-AzureADAdministrativeUnit)
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get all Azure AD user member of the admin unit TP-AL
        C:\PS> Get-AzureADAdministrativeUnit -Filter "displayname eq 'TP-AL'" | Get-AzureADAdministrativeUnitAllMembers
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.AdministrativeUnit]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectId
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectId) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject parameter - exiting"
            }
            $params = @{
                API = "administrativeUnits"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $parameter = $inputobject.ObjectId + "/members?`$top=999"
            } elseif ($ObjectId) {
                $parameter = $ObjectId.guid + "/members?`$top=999"
            }
            $params.add('APIParameter',$parameter)
            Invoke-APIMSGraphBeta @params
        }
    }
    Function New-AzureADAdministrativeUnitCustom {
    <#
        .SYNOPSIS
        Create a new Azure AD Administrative Unit
     
        .DESCRIPTION
        Create a new Administrative Unit with hidden membership managed. if used, only members of the admin unit can see the Admin Unit members. Azure AD user account with advanced roles (Global reader, global administrator..) can still see the Admin Unit members.
         
        .PARAMETER displayName
        -displayName String
        display name of the new admin unit
         
        .PARAMETER description
        -description String
        description name of the new admin unit
         
        .PARAMETER Hidden
        -Hidden {switch}
        use the swith to set administrative unit as hidden
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Create a new Administrative Unit with hidden membership called testHidden
        C:\PS> New-AzureADAdministrativeUnitCustom -displayName "testHidden" -description "Hidden Test Admin unit" -Hidden
         
        .EXAMPLE
        Create a new Administrative Unit membership called test
        C:\PS> New-AzureADAdministrativeUnitCustom -displayName "test" -description "Test Admin unit"
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [String]$displayName,
            [parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [String]$description,
            [parameter(Mandatory=$false)]
                [switch]$Hidden
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $body = [PSCustomObject]@{
                displayName = $displayName
                description = $description
            }
            if ($Hidden.IsPresent) {
                $body | add-member -NotePropertyName visibility -NotePropertyValue "HiddenMembership"
            }
            $params = @{
                API = "administrativeUnits"
                Method = "POST"
                APIBody = (ConvertTo-Json -InputObject $body -Depth 100)
            }
            write-verbose -Message "JSON Body : $(ConvertTo-Json -InputObject $body -Depth 100)"
            Invoke-APIMSGraphBeta @params
        } 
    }
    Function Get-AzureADAdministrativeUnitHidden {
    <#
        .SYNOPSIS
        Get Administrative Units with hidden membership
     
        .DESCRIPTION
        Get Administratives Unit with hidden membership. Only members of the admin unit can see the Admin Unit members. Azure AD user account with advanced roles (Global reader, global administrator..) can still see the Admin Unit members.
         
        .PARAMETER public
        -public boolean
        choose if you want to display Administrative Unit with hidden membership or public membership
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.AdministrativeUnit
        Microsoft.Open.AzureAD.Model.AdministrativeUnit object (for instance created by Get-AzureADAdministrativeUnit)
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get Administrative Units with hidden membership
        C:\PS> Get-AzureADAdministrativeUnitHidden
         
        .EXAMPLE
        Get Administrative Units with public membership
        C:\PS> Get-AzureADAdministrativeUnitHidden -public $true
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.AdministrativeUnit]$inputobject,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [bool]$public
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $params = @{
                API = "administrativeUnits"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $params.Add('APIParameter',$inputobject.ObjectId)  
            }
            $adminunitobj = Invoke-APIMSGraphBeta @params
            if (($public -eq $false) -and !($inputobject)) {
                $adminunitobj | Where-Object { $_.visibility -eq "HiddenMembership"}
            } elseif (($public -eq $true) -and !($inputobject)) {
                $adminunitobj | Where-Object { $_.visibility -ne "HiddenMembership"}
            } else {
                $adminunitobj
            }
        }
    }
    Function Get-AzureADConnectCloudProvisionningServiceSyncSchema {
    <#
        .SYNOPSIS
        Get Azure AD Connect Cloud Sync schema for a provisionning agent
     
        .DESCRIPTION
        Get all properties of an Azure AD Connect Cloud Sync schema for a provisionning agent (synchronizationRules, schema, objectMappings rules...)
         
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the SPN used by your provisionning agent
         
        .PARAMETER OnPremADFQDN
        -OnPremADFQDN string
        FQDN of your on premise AD Domain managed through Azure AD Connect Cloud Provisionning (provisionning agent must already be declared)
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get Azure AD Connect Cloud Sync schema for a provisionning agent of domain mydomain.tld
        C:\PS> Get-AzureADConnectCloudProvisionningServiceSyncSchema -OnPremADFQDN mydomain.tld
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$OnPremADFQDN,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [GUID]$ObjectID
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($OnPremADFQDN) -and !($ObjectID)) {
                throw "Use OnPremADFQDN or ObjectID parameter - exiting"
            }
            $params = @{
                API = "serviceprincipals"
                Method = "GET"
            }
            if ($OnPremADFQDN) {
                $params.add('APIParameter',"?`$filter=startswith(Displayname,'$($OnPremADFQDN)')")
            } elseif ($ObjectID) {
                $params.add('APIParameter',$ObjectID)
            }
            $spnobj = Invoke-APIMSGraphBeta @params
            write-verbose -message "SPN ID : $($spnobj.id)"
            $params['APIParameter'] = "$($spnobj.id)/synchronization/jobs/?`$filter=templateId eq 'AD2AADProvisioning'"
            $syncjobsobj = Invoke-APIMSGraphBeta @params
            write-verbose -message "AD2AADProvisioning ID : $syncjobsobj.id"
            if ($syncjobsobj.id -notlike "AD2AADProvisioning.*") {
                throw "Azure AD Service Principal does not seem to be an AD2AAD provisionning object - exiting"
            }
            $params['APIParameter'] = "$($spnobj.id)/synchronization/jobs/$($syncjobsobj.id)/schema"
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADConnectCloudProvisionningServiceSyncDefaultSchema {
        <#
            .SYNOPSIS
            Get Azure AD Connect Cloud Sync default schema (Azure AD Connect Cloud Sync template)
         
            .DESCRIPTION
            Get all properties of the Azure AD Connect Cloud Sync default schema - Azure AD Connect Cloud Sync template (synchronizationRules, schema, objectMappings rules...)
             
            .PARAMETER ObjectId
            -ObjectId guid
            GUID of the SPN used by your provisionning agent
             
            .PARAMETER OnPremADFQDN
            -OnPremADFQDN string
            FQDN of your on premise AD Domain managed through Azure AD Connect Cloud Provisionning (provisionning agent must already be declared)
                 
            .OUTPUTS
            TypeName : System.Management.Automation.PSCustomObject
                         
            .EXAMPLE
            Get Azure AD Connect Cloud Sync default schema of domain mydomain.tld
            C:\PS> Get-AzureADConnectCloudProvisionningServiceSyncDefaultSchema -OnPremADFQDN mydomain.tld
        #>

            [cmdletbinding()]
            Param (
                [Parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                    [string]$OnPremADFQDN,
                [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                    [GUID]$ObjectID
            )
            process {
                Test-AzureADAccessTokenExpiration | out-null
                if (!($OnPremADFQDN) -and !($ObjectID)) {
                    throw "Use OnPremADFQDN or ObjectID parameter - exiting"
                }
                $params = @{
                    API = "serviceprincipals"
                    Method = "GET"
                }
                if ($OnPremADFQDN) {
                    $params.add('APIParameter',"?`$filter=startswith(Displayname,'$($OnPremADFQDN)')")
                } elseif ($ObjectID) {
                    $params.add('APIParameter',$ObjectID)
                }
                $spnobj = Invoke-APIMSGraphBeta @params
                write-verbose -message "SPN ID : $($spnobj.id)"
                $params['APIParameter'] = "$($spnobj.id)/synchronization/templates/AD2AADProvisioning/"
                Invoke-APIMSGraphBeta @params
            }
    }
    Function Update-AzureADConnectCloudProvisionningServiceSyncSchema {
    <#
        .SYNOPSIS
        Update your Azure AD Connect Cloud Sync schema for a provisionning agent
     
        .DESCRIPTION
        Update your Azure AD Connect Cloud Sync schema for a provisionning agent (synchronizationRules, schema, objectMappings rules...)
         
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the SPN used by your provisionning agent
         
        .PARAMETER OnPremADFQDN
        -OnPremADFQDN string
        FQDN of your on premise AD Domain managed through Azure AD Connect Cloud Provisionning (provisionning agent must already be declared)
         
        .PARAMETER inputobject
        -inputobject PSCustomObject
        a PSCustom Object containing your new schema to upload
        .OUTPUTS
           None (except warning)
                 
        .EXAMPLE
        Update your Azure AD Connect Cloud Sync schema for provisionning agent of domain mydomain.tld, new schema available in $schema object
        C:\PS> Update-AzureADConnectCloudProvisionningServiceSyncSchema -OnPremADFQDN mydomain.tld -inputobject $schema
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$OnPremADFQDN,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [GUID]$ObjectID,
            [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
                [pscustomobject]$inputobject
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($OnPremADFQDN) -and !($ObjectID)) {
                throw "Use OnPremADFQDN or ObjectID parameter - exiting"
            }
            if ($inputobject.'@odata.context' -notlike "*AD2AADProvisioning*") {
                throw "PSCustomObject inputobject seems to be invalid (not containing an Azure AD Cloud Provisionning Schema) - exiting"
            }
            $params = @{
                API = "serviceprincipals"
                Method = "GET"
            }
            if ($OnPremADFQDN) {
                $params.add('APIParameter',"?`$filter=startswith(Displayname,'$($OnPremADFQDN)')")
            } elseif ($ObjectID) {
                $params.add('APIParameter',$ObjectID)
            }
            $spnobj = Invoke-APIMSGraphBeta @params
            write-verbose -message "SPN ID : $($spnobj.id)"
            $params['APIParameter'] = "$($spnobj.id)/synchronization/jobs/?`$filter=templateId eq 'AD2AADProvisioning'"
            $syncjobsobj = Invoke-APIMSGraphBeta @params
            write-verbose -message "AD2AADProvisioning ID : $syncjobsobj.id"
            if ($syncjobsobj.id -notlike "AD2AADProvisioning.*") {
                throw "Azure AD Service Principal does not seem to be an AD2AAD provisionning object - exiting"
            }
            $params['method'] = "PUT"
            $params['APIParameter'] = "$($spnobj.id)/synchronization/jobs/$($syncjobsobj.id)/schema"
            $params.add('APIBody',(ConvertTo-Json -InputObject $inputobject -Depth 100))
            Invoke-APIMSGraphBeta @params
        }
    }
    Function New-AzureADObjectDeltaView {
    <#
        .SYNOPSIS
        Create a new delta view for an Azure AD object
     
        .DESCRIPTION
        Create a new delta view for an Azure AD object. It can be used on several objects (groups, users, administrative units...) to retrieve change information occured between two moments (properties updated/removed/added, objects updated/removed/added).
        This cmdlet create the initial view (available at server side for 30 days maximum) and the cmdlet Get-AzureADObjectDeltaView will retrieve the changes occured between the first view creation.
         
        .PARAMETER ObjectType
        -ObjectType String {"Users","Groups","AdministrativeUnits"}
        target object type you want to use for the delta view
         
        .PARAMETER SelectProperties
        -SelectProperties String - array of strings
        object properties you want to watch, by default all properties will be followed
     
        .PARAMETER FilterIDs
        -FilterIDs String - array of strings
        object GUID you want to watch, by default all object from the object type selected will be followed
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Create an initial delta view for manager and department properties of all users objects
        C:\PS> New-AzureADObjectDeltaView -ObjectType Users -SelectProperties @("manager","department")
         
        .EXAMPLE
        Create an initial delta view for manager and department properties of fb01091c-a9b2-4cd2-bbc9-130dfc91452a and 2092d280-2821-45ae-9e47-e9433a65868d users objects
        C:\PS> New-AzureADObjectDeltaView -ObjectType Users -SelectProperties @("manager","department") -FilterIDs @("fb01091c-a9b2-4cd2-bbc9-130dfc91452a","2092d280-2821-45ae-9e47-e9433a65868d") -Verbose
    #>

        [cmdletbinding()]
        param (
            [parameter(Mandatory=$true)]
            [validateSet("Users","Groups","AdministrativeUnits")]
                [string]$ObjectType,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string[]]$SelectProperties,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string[]]$FilterIDs
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $params = @{
                API = $ObjectType
                Method = "GET"
            }
            if ($SelectProperties) {
                if ($SelectProperties.Count -gt 1) {
                    $properties = $SelectProperties -join ","
                } else {
                    $properties = $SelectProperties
                }
                Write-verbose -Message "Select properties : $($properties)"
                $parameterproperties = "`$select=" + $properties
            }
            if ($FilterIDs) {
                if ($FilterIDs.count -gt 1) {
                        $UpdFilterIDs = @()
                    foreach ($FilterID in $FilterIDs) {
                        $UpdFilterIDs += "id eq '{0}'" -f $FilterID
                    }
                    $properties = $UpdFilterIDs -join " or "
                } else {
                    $properties = "id eq '$($FilterIDs)'"
                }
                Write-verbose -Message "Select filter : $($properties)"
                $parameterfilters = "`$filter=" + $properties
            }
            if ($parameterproperties -and $parameterfilters) {
                $parameters = "delta?" + $parameterproperties + "&" + $parameterfilters
            } elseif ($parameterproperties -or $parameterfilters) {
                $parameters = "delta?" + $parameterproperties + $parameterfilters
            } else {
                $parameters = "delta"
            }
            Write-verbose -Message "parameters : $($parameters)"
            $params.Add('APIParameter',$parameters) 
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADObjectDeltaView {
    <#
        .SYNOPSIS
        Get all changes from a delta view for an Azure AD object
     
        .DESCRIPTION
        Get all changes from a delta view for an Azure AD object. A delta view for an Azure AD object must be created first with New-AzureADObjectDeltaView.
        It can be used on several objects (groups, users, administrative units...) to retrieve change information occured between two moments (properties updated/removed/added, objects updated/removed/added).
        A maximum of 30 days changes can be retrieved.
         
        .PARAMETER inputobject
        -inputobject PSCustomObject
        PSCustomObject generated previously with New-AzureADObjectDeltaView cmdlet
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get all updates from an initial delta view for manager and department properties of fb01091c-a9b2-4cd2-bbc9-130dfc91452a and 2092d280-2821-45ae-9e47-e9433a65868d users objects previously saved in $delta
        C:\PS> $delta = New-AzureADObjectDeltaView -ObjectType Users -SelectProperties @("manager","department") -FilterIDs @("fb01091c-a9b2-4cd2-bbc9-130dfc91452a","2092d280-2821-45ae-9e47-e9433a65868d") -Verbose
        C:\PS> Get-AzureADDeltaFromView -inputobject $delta
    #>

        [cmdletbinding()]
        param (
            [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [ValidateNotNullOrEmpty()]
                $inputobject
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($inputobject[-1].deltaLink)) {
                throw "Not able to find deltalink property of the object - please use New-AzureADObjectDeltaView cmdlet to generate a view first - exiting"
            } else {
                write-verbose -Message "Delta link : $($inputobject[-1].deltaLink)"
                Invoke-APIMSGraphBetaPaging -Paging $inputobject[-1].deltaLink
            }
        }
    }
    Function Get-AzureADDynamicGroup {
    <#
        .SYNOPSIS
        Retrieve information about an Azure AD security dynamic group
     
        .DESCRIPTION
        Retrieve all available properties about an existing security group with dynamic membership
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
     
        .PARAMETER Displayname
        -DisplayName String
        Displayname of an existing Azure AD Group object
     
        .PARAMETER All
        -All switch
        swith parameter that can be used to retrieve all existing Azure AD security group with dynamic membership rule
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get dynamic group with ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADDynamicGroup -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        Get all security group with dynamic membership
        C:\PS> Get-AzureADDynamicGroup -all
     
        .EXAMPLE
        Get dynamic group with Dynam_test display name
        C:\PS> Get-AzureADDynamicGroup -DisplayName "Dynam_test"
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$DisplayName,
            [parameter(Mandatory=$false)]
                [switch]$All
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject) -and !($all.IsPresent) -and !($DisplayName)) {
                throw "Please use ObjectID or inputobject or DisplayName parameter or All switch - exiting"
            }
            $GroupFilter = "?`$filter=groupTypes/any(c:c+eq+'DynamicMembership')"
            $params = @{
                API = "groups"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $params.add('APIParameter',$inputobject.ObjectId)
            } elseif ($ObjectID) {
                $params.add('APIParameter',$ObjectID)
            } elseif ($DisplayName) {
                $params.add('APIParameter',$GroupFilter + "and displayName eq '$($DisplayName)'")
            } else {
                $params.add('APIParameter',$GroupFilter)
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function New-AzureADDynamicGroup {
    <#
        .SYNOPSIS
        Create a new Azure AD security dynamic group
     
        .DESCRIPTION
        Create a new Azure AD security dynamic group and set its membership rule
         
        .PARAMETER Description
        -Description String
        Description of the new group
     
        .PARAMETER Displayname
        -DisplayName String
        Displayname of the new group
     
        .PARAMETER MembershipRule
        -MembershipRule string
        Membership rule (string) of the new dynamic group. More info about rule definition here : https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/groups-dynamic-membership
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Create a new dynamic group Dynam_test5 with a membership rule based on user extensionAttribute9 value "test"
        C:\PS> New-AzureADDynamicGroup -DisplayName "Dynam_test5" -Description "Dynam_test5" -MemberShipRule '(user.extensionAttribute9 -eq "test")'
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [ValidateNotNullOrEmpty()]
                [string]$DisplayName,
            [parameter(Mandatory=$true)]
                [ValidateNotNullOrEmpty()]
                [string]$Description,
            [parameter(Mandatory=$true)]
                [ValidateNotNullOrEmpty()]
                [string]$MemberShipRule
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $ExistingGroup = Get-AzureADDynamicGroup -DisplayName $DisplayName
            If ($ExistingGroup.id) {
                throw "$($DisplayName) group is already existing with ID $($ExistingGroup.id)"
            } Else {
                $tmpbody = @{
                    description = $Description
                    displayName = $DisplayName
                    groupTypes = @("DynamicMembership")
                    mailEnabled = $false
                    mailNickname = ($DisplayName -replace '[^a-zA-Z0-9]', '')
                    membershipRule = $MemberShipRule
                    membershipruleProcessingState = "On"
                    SecurityEnabled = $true
                }
                $params = @{
                    API = "groups"
                    Method = "POST"
                    APIBody = $tmpbody | ConvertTo-Json -Depth 99
                }
                write-verbose -Message $params.APIBody
                Invoke-APIMSGraphBeta @params
            }
        }
    }
    Function New-AzureADMSGroupCustom {
    <#
        .SYNOPSIS
        Create a new Azure AD Office 365 dynamic or static group
     
        .DESCRIPTION
        Create a new Azure AD Office 365 dynamic or static group with resourceBehaviorOptions and resourceProvisioningOptions support : https://docs.microsoft.com/en-us/graph/group-set-options
         
        .PARAMETER Description
        -Description String
        Description of the new group
     
        .PARAMETER Displayname
        -DisplayName String
        Displayname of the new group
     
        .PARAMETER MembershipRule
        -MembershipRule string
        Membership rule (string) of the new dynamic group. More info about rule definition here : https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/groups-dynamic-membership
         
        .PARAMETER MailNickname
        -MailNickname string
        mail nickname to be used for the group. if not defined, the displayname value is used.
 
        .PARAMETER groupType
        -groupType string ("StaticMembership","DynamicMembership")
        use "StaticMembership" value to create a standard group with classic members, use "DynamicMembership" value to create a dynamic group with members managed by rules. when using "DynamicMembership", the parameter "MembershipRule" must be use also to define the rule
         
        .PARAMETER visibility
        -visibility string ("private","public","Hiddenmembership")
        use "private" to create a private group, "public" for a public group or "Hiddenmembership" for private group with hidden membership
         
        .PARAMETER resourceBehaviorOptions
        -resourceBehaviorOptions array of string ("AllowOnlyMembersToPost","HideGroupInOutlook","WelcomeEmailDisabled","SubscribeNewGroupMembers")
        more information here : https://docs.microsoft.com/en-us/graph/group-set-options
         
        .PARAMETER resourceProvisioningOptions
        -resourceProvisioningOptions array of string ("Teams")
        more information here : https://docs.microsoft.com/en-us/graph/group-set-options
 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Create a new static group testapigroup4 with resourceBehaviorOptions set
        C:\PS> New-AzureADMSGroupCustom -DisplayName "testapigroup4" -Description "testapigroup4" -resourceBehaviorOptions @("AllowOnlyMembersToPost","HideGroupInOutlook","WelcomeEmailDisabled")
 
        .EXAMPLE
        Create a new dynamic group testapigroup5 with resourceBehaviorOptions and resourceProvisioningOptions set
        C:\PS> New-AzureADMSGroupCustom -DisplayName "testapigroup5" -Description "testapigroup5" -resourceBehaviorOptions @("AllowOnlyMembersToPost","HideGroupInOutlook","WelcomeEmailDisabled") -MailNickname "testapigroup55" -groupType DynamicMembership -visibility public -MemberShipRule "(user.userType -eq `"Guest`")" -resourceProvisioningOptions Teams -Verbose
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [ValidateNotNullOrEmpty()]
                [string]$DisplayName,
            [parameter(Mandatory=$true)]
                [ValidateNotNullOrEmpty()]
                [string]$Description,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$MailNickname,
            [parameter(Mandatory=$false)]
                [validateSet("StaticMembership","DynamicMembership")]
                [string]$groupType = "StaticMembership",
            [parameter(Mandatory=$false)]
            [validateSet("private","public","Hiddenmembership")]
                [string]$visibility = "private",
            [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$MemberShipRule,
            [parameter(Mandatory=$false)]
                [validateSet("AllowOnlyMembersToPost","HideGroupInOutlook","WelcomeEmailDisabled","SubscribeNewGroupMembers")]
                    [string[]]$resourceBehaviorOptions,
            [parameter(Mandatory=$false)]
                [validateSet("Teams")]
                    [string[]]$resourceProvisioningOptions
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (($groupType -eq "DynamicMembership") -and !($MemberShipRule)) {
                throw "Please set MemberShipRule parameter when using 'DynamicMembership' value as groupType parameter"
            }
            $ExistingGroup = Get-AzureADGroup -Filter "displayname eq '$DisplayName'"
            if ($ExistingGroup) {
                throw "$($DisplayName) group is already existing with ID $($ExistingGroup.ObjectId)"
            }
            if (!($MailNickname)) {
                $MailNickname = ($DisplayName -replace '[^a-zA-Z0-9]', '')
            }
            if ($groupType -eq "DynamicMembership") {
                $groupTypes = @("Unified",$groupType)
            } else {
                $groupTypes = @("Unified")
            }
            $tmpbody = @{
                description = $Description
                displayName = $DisplayName
                groupTypes = $groupTypes
                mailEnabled = $true
                mailNickname = $MailNickname
                SecurityEnabled = $false
                visibility = $visibility
            }
            if ($MemberShipRule) {
                $tmpbody.Add("membershipRule",$MemberShipRule)
                $tmpbody.add("membershipruleProcessingState","on")
            }
            if ($resourceBehaviorOptions) {
                $tmpbody.Add("resourceBehaviorOptions",$resourceBehaviorOptions)
            }
            if ($resourceProvisioningOptions) {
                $tmpbody.Add("resourceProvisioningOptions",$resourceProvisioningOptions)
            }
            $params = @{
                API = "groups"
                Method = "POST"
                APIBody = $tmpbody | ConvertTo-Json -Depth 99
            }
            write-verbose -Message $params.APIBody
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Set-AzureADMSGroupCustom {
    <#
        .SYNOPSIS
        Update an existing Azure AD Office 365 dynamic or static group
     
        .DESCRIPTION
        Update an existing Azure AD Office 365 dynamic or static group with resourceExchangeOptions support : https://docs.microsoft.com/en-us/graph/api/group-update?view=graph-rest-beta&tabs=http
         
        .PARAMETER NewDescription
        -NewDescription String
        Updated description of the group
     
        .PARAMETER NewDisplayname
        -NewDisplayname String
        Updated displayname of the new group
             
        .PARAMETER NewMailNickname
        NewMailNickname string
        updated mail nickname to be used for the group. if not defined, the new displayname value is used.
 
        .PARAMETER Newvisibility
        -Newvisibility string ("private","public","Hiddenmembership")
        use "private" to update to a private group, "public" for a public group or "Hiddenmembership" for private group with hidden membership
         
        .PARAMETER ResourceExchangeOptions
        -ResourceExchangeOptions hastable
        available key name : allowExternalSenders, autoSubscribeNewMembers, hideFromAddressLists, hideFromOutlookClients, isSubscribedByMail, unseenCount
        available value : boolean for all key except unseenCount int32
         
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Update a group to set several Exchange options
        C:\PS> Get-AzureADGroup -ObjectId fd04a7ae-65e2-44ba-a940-b75efbd95d7e | set-AzureADMSGroupCustom -ResourceExchangeOptions @{"hideFromAddressLists"=$true;"allowExternalSenders"=$false;"autoSubscribeNewMembers"=$false;"hideFromOutlookClients"=$true;"isSubscribedByMail"=$false;"unseenCount"=10}
 
        .EXAMPLE
        Update a group to set a new description
        C:\PS> Get-AzureADGroup -ObjectId fd04a7ae-65e2-44ba-a940-b75efbd95d7e | set-AzureADMSGroupCustom -NewDescription "testapigroup55 test"
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [Parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$NewDisplayName,
            [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$NewDescription,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$NewMailNickname,
            [parameter(Mandatory=$false)]
            [validateSet("private","public","Hiddenmembership")]
                [string]$Newvisibility,
            [parameter(Mandatory=$false,HelpMessage="boolean value for all keys except unseenCount : int, supported key name : allowExternalSenders, autoSubscribeNewMembers, hideFromAddressLists, hideFromOutlookClients, isSubscribedByMail, unseenCount")]
                [Hashtable]$ResourceExchangeOptions
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject - exiting"
            }
            if (!($NewDisplayName) -and !($NewDescription) -and !($NewMailNickname) -and !($ResourceExchangeOptions)) {
                throw "Please select at least one parameter to update : NewDisplayName, NewDescription, NewMailNickname, ResourceExchangeOptions - exiting"
            }
            if ($ResourceExchangeOptions -and ($NewDisplayName -or $NewDescription -or $NewMailNickname -or $Newvisibility)) {
                throw "you cannot use ResourceExchangeOptions with other options - exiting"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $ObjectID
            }
            if (!($ExistingGroup)) {
                throw "Azure AD Group not existing in directory."
            } else {
                if ($ResourceExchangeOptions) {
                    foreach ($option in $ResourceExchangeOptions.Keys) {
                        $tmpbody = @{
                            $option = $ResourceExchangeOptions[$option]
                        }
                        $params = @{
                            API = "groups"
                            Method = "PATCH"
                            APIParameter = $ExistingGroup.ObjectId
                            APIBody = $tmpbody | ConvertTo-Json -Depth 99
                        }
                        write-verbose -Message $params.APIBody
                        Invoke-APIMSGraphBeta @params
                    }
                } else {
                    $tmpbody = @{}
                    if ($NewDisplayName) {
                        $tmpbody.Add("displayName", $newDisplayName)
                    }
                    if ($NewDescription) {
                        $tmpbody.Add("description", $NewDescription)
                    }
                    if ($Newvisibility) {
                        $tmpbody.Add("visibility", $Newvisibility)
                    }
                    if ($NewMailNickname) {
                        $tmpbody.Add("mailNickname", $NewMailNickname)
                    } elseif ($NewDisplayName -and !($NewMailNickname)) {
                        $tmpbody.Add("mailNickname", ($NewDisplayName -replace '[^a-zA-Z0-9]', ''))
                    }
                    $params = @{
                        API = "groups"
                        Method = "PATCH"
                        APIBody = $tmpbody | ConvertTo-Json -Depth 99
                        APIParameter = $ExistingGroup.ObjectId
                    }
                    write-verbose -Message $params.APIBody
                    Invoke-APIMSGraphBeta @params
                }
            }
        }
    }
    Function Remove-AzureADDynamicGroup {
    <#
        .SYNOPSIS
        Delete an existing Azure AD security dynamic group
     
        .DESCRIPTION
        Delete an existing Azure AD security dynamic group
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
         
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Remove an existing group named Dynam_test2 (displayname)
        C:\PS> Get-AzureADGroup -SearchString 'Dynam_test2' | Remove-AzureADDynamicGroup
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject - exiting"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $ObjectID
            }
            if ($ExistingGroup.id) {
                $params = @{
                    API = "groups"
                    Method = "DELETE"
                    APIParameter = $ExistingGroup.id
                }
                Invoke-APIMSGraphBeta @params
            } else {
                throw "Azure AD Group not existing in directory"
            }
        }
    }
    Function Set-AzureADDynamicGroup {
    <#
        .SYNOPSIS
        Update properties of an existing Azure AD security dynamic group
     
        .DESCRIPTION
        Update properties of an existing Azure AD security dynamic group, including processing state of the rule.
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
         
        .PARAMETER NewDescription
        -NewDescription String
        Description of the new group
     
        .PARAMETER NewDisplayname
        -NewDisplayName String
        Displayname of the new group
     
        .PARAMETER NewMembershipRule
        -NewMembershipRule string
        Membership rule (string) of the dynamic group. More info about rule definition here : https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/groups-dynamic-membership
         
        .PARAMETER DisableRuleProcessingState
        -DisableRuleProcessingState Switch
        Disable processing state of the current rule
     
        .PARAMETER EnableRuleProcessingState
        -EnableRuleProcessingState Switch
        Enable processing state of the current rule
     
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Update existing dynamic group 17a58653-3654-40bd-85ce-333ece486793 with a new description and membership rule
        C:\PS> Set-AzureADDynamicGroup -ObjectId 17a58653-3654-40bd-85ce-333ece486793 -NewDescription "test description" -NewMemberShipRule '(user.extensionAttribute1 -eq "test2")'
     
        .EXAMPLE
        Update existing dynamic group 17a58653-3654-40bd-85ce-333ece486793 to disable processing state of the current rule
        C:\PS> Set-AzureADDynamicGroup -ObjectId 17a58653-3654-40bd-85ce-333ece486793 -DisableRuleProcessingState
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [Parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$NewDisplayName,
            [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$NewDescription,
            [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$NewMemberShipRule,
            [parameter(Mandatory=$false)]
                [switch]$DisableRuleProcessingState,
            [parameter(Mandatory=$false)]
                [switch]$EnableRuleProcessingState
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject - exiting"
            }
            if (!($NewDisplayName) -and !($NewDescription) -and !($NewMemberShipRule) -and !($DisableRuleProcessingState) -and !($EnableRuleProcessingState)) {
                throw "Please select at least one parameter to update : NewDisplayName, NewDescription, NewMemberShipRule, DisableRuleProcessingState, EnableRuleProcessingState - exiting"
            }
            if ($DisableRuleProcessingState -and $EnableRuleProcessingState) {
                throw "Please select between DisableRuleProcessingState and EnableRuleProcessingState parameters - exiting"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $ObjectID
            }
            if ($ExistingGroup.id) {
                $tmpbody = @{}
                if ($NewDisplayName) {
                    $tmpbody.add('displayName',$NewDisplayName)
                    $tmpbody.add('mailNickname',($NewDisplayName -replace '[^a-zA-Z0-9]', ''))
                }
                if ($NewDescription) {
                    $tmpbody.add('description',$NewDescription)
                }
                if ($NewMemberShipRule) {
                    $tmpbody.add('membershipRule',$NewMemberShipRule)
                }
                if ($DisableRuleProcessingState) {
                    $tmpbody.add('membershipruleProcessingState',"Paused")
                }
                if ($EnableRuleProcessingState) {
                    $tmpbody.add('membershipruleProcessingState',"On")
                }
                $params = @{
                    API = "groups"
                    Method = "PATCH"
                    APIParameter = $ExistingGroup.id
                    APIBody = $tmpbody | ConvertTo-Json -Depth 99
                }
                write-verbose -Message $params.APIBody
                Invoke-APIMSGraphBeta @params
            } else {
                throw "Azure AD Group not existing in directory"
            }
        }
    }
    Function Test-AzureADUserForGroupDynamicMembership {
    <#
        .SYNOPSIS
        Check if a Azure AD user is a member of an Azure AD security dynamic group
     
        .DESCRIPTION
        Check if a Azure AD user is a member of an Azure AD security dynamic group
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
     
        .PARAMETER MemberID
        -MemberID Guid
        Guid of an Azure AD user account that you want to test from a membership perspective of the group
     
        .PARAMETER MembershipRule
        -MembershipRule string
        Membership rule (string) of dynamic group you want to test. More info about rule definition here : https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/groups-dynamic-membership
         
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Test if ca57f8b0-0c86-4677-8167-7d37534bd3bc object user account is member of 53cf95f1-49be-463e-9856-77c2b2c3e4a0 dynamic group using a specific rule
        C:\PS> Test-AzureADUserForGroupDynamicMembership -ObjectID 53cf95f1-49be-463e-9856-77c2b2c3e4a0 -MemberID ca57f8b0-0c86-4677-8167-7d37534bd3bc -MemberShipRule 'user.extensionAttribute9 -eq "test2"'
     
        .EXAMPLE
        Test if ca57f8b0-0c86-4677-8167-7d37534bd3bc object user account is member of 53cf95f1-49be-463e-9856-77c2b2c3e4a0 dynamic group
        C:\PS> Test-AzureADUserForGroupDynamicMembership -ObjectID 53cf95f1-49be-463e-9856-77c2b2c3e4a0 -MemberID ca57f8b0-0c86-4677-8167-7d37534bd3bc
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [parameter(Mandatory=$true)]
                [guid]$MemberID,
            [parameter(Mandatory=$false)]
                [ValidateNotNullOrEmpty()]
                [string]$MemberShipRule
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject - exiting"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADDynamicGroup -ObjectId $ObjectID
            }
            if ($ExistingGroup.id) {
                try {
                    $existinguser = get-azureaduser -objectid $MemberID
                } catch {
                    throw "Azure AD User not exising in directory"
                }
                $tmpbody = @{
                    memberId = $existinguser.objectid
                }
                $params = @{
                    API = "groups"
                    Method = "POST"
                }
                if ($MemberShipRule) {
                    $tmpbody.add('membershipRule',$MemberShipRule)
                    $params.add('APIParameter',"evaluateDynamicMembership")
                } else {
                    $params.add('APIParameter',($ExistingGroup.id + "/evaluateDynamicMembership"))
                }
                $params.add('APIBody', ($tmpbody | ConvertTo-Json -Depth 99))
                write-verbose -Message $params.APIBody
                Invoke-APIMSGraphBeta @params
            } else {
                throw "Azure AD Group not existing in directory"
            }
        }
    }
    Function Get-AzureADGroupMembersWithLicenseErrors {
    <#
        .SYNOPSIS
        Get all Azure AD User with licensing error members of a particular group
        Get all Azure AD Group containing users with licensing errors
     
        .DESCRIPTION
        Get all Azure AD User with licensing error members of a particular group
        Get all Azure AD Group containing users with licensing errors
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
     
        .PARAMETER All
        -All Switch
        Use this switch instead of ObjectID to retrieve All groups containing users with licensing errors
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get licensing error info for members of Azure AD group fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADGroupMembersWithLicenseErrors -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        Get licensing error info for members of Azure AD group fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureAdGroup -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a | Get-AzureADGroupMembersWithLicenseErrors
     
        .EXAMPLE
        Get groups containing users with licensing errors
        C:\PS> Get-AzureADGroupMembersWithLicenseErrors -All
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [parameter(Mandatory=$false)]
                [switch]$All
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject) -and !($all)) {
                throw "Please use ObjectID or inputobject parameters or All switch - exiting"
            }
            if ($ObjectID -and $inputobject) {
                throw "Please choose between ObjectID or inputobject parameters - exiting"
            }
            $params = @{
                API = "groups"
                Method = "GET"
            }
            if ($all) {
                $params.add('APIParameter',"?`$filter=hasMembersWithLicenseErrors+eq+true")
            } else {
                if ($inputobject.ObjectID) {
                    $ExistingGroup = Get-AzureADGroup -ObjectId $inputobject.ObjectID
                } elseif ($ObjectID) {
                    $ExistingGroup = Get-AzureADGroup -ObjectId $ObjectID
                }
                if ($ExistingGroup.ObjectID) {
                    $params.add('APIParameter', $ExistingGroup.ObjectID + "/membersWithLicenseErrors")
                } else {
                    throw "Azure AD Group not existing in directory"
                }
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADGroupLicenseDetail {
    <#
        .SYNOPSIS
        Get licensing info of a particular group
     
        .DESCRIPTION
        Get all licening info (skuid applied, service plans disabled) for a particular Azure AD Group
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get licensing info for Azure AD group fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADGroupLicenseDetail -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        Get licensing info for Azure AD group fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureAdGroup -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a | Get-AzureADGroupLicenseDetail
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject parameters - exiting"
            }
            if ($ObjectID -and $inputobject) {
                throw "Please choose between ObjectID or inputobject parameters - exiting"
            }
            $params = @{
                API = "groups"
                Method = "GET"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $ObjectID
            }
            if ($ExistingGroup.ObjectID) {
                $params.add('APIParameter', $ExistingGroup.ObjectID + "?`$select=assignedLicenses")
            } else {
                throw "Azure AD Group not existing in directory"
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Set-AzureADGroupLicense {
    <#
        .SYNOPSIS
        Add or remove a license on an Azure AD Group
     
        .DESCRIPTION
        Add or remove a license (skuid applied, or service plans to be disabled) for a particular Azure AD Group
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.Group
        Microsoft.Open.AzureAD.Model.Group generated previously with Get-AzureADGroup cmdlet
     
        .PARAMETER AddLicense
        -AddLicense switch
        Use the switch to add a new license to the group
     
        .PARAMETER RemoveLicense
        -RemoveLicense switch
        Use the switch to remove an existing license from the group
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD Group object
     
        .PARAMETER DisabledPlans
        -DisabledPlans Guid - array of guids
        Guid / array of guids containing the guid of the service plans to be disabled in the SKU provided. To be used only with AddLicense switch.
        You cannot remove plans disabled from the sku / group. you must remove totally the license (sku) then add it using the new disabled plans.
     
        .PARAMETER SkuID
        -SkuID Guid
        Guid of the SKU to be added or removed to / from the group. Mandatory parameter to be used with AddLicense and RemoveLicense switchs
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Remove SkuID license 84a661c4-e949-4bd2-a560-ed7766fcaf2b from the group 53cf95f1-49be-463e-9856-77c2b2c3e4a0
        C:\PS> Set-AzureADGroupLicense -ObjectID 53cf95f1-49be-463e-9856-77c2b2c3e4a0 -RemoveLicense -SkuID 84a661c4-e949-4bd2-a560-ed7766fcaf2b -Verbose
     
        .EXAMPLE
        Remove SkuID license 84a661c4-e949-4bd2-a560-ed7766fcaf2b from the group 53cf95f1-49be-463e-9856-77c2b2c3e4a0
        C:\PS> Get-AzureAdGroup -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a | Set-AzureADGroupLicense -RemoveLicense -SkuID 84a661c4-e949-4bd2-a560-ed7766fcaf2b -Verbose
     
        .EXAMPLE
        Add license sku 84a661c4-e949-4bd2-a560-ed7766fcaf2b to the group 53cf95f1-49be-463e-9856-77c2b2c3e4a0 and disable service plans 113feb6c-3fe4-4440-bddc-54d774bf0318, 932ad362-64a8-4783-9106-97849a1a30b9 from this sku
        C:\PS> Set-AzureADGroupLicense -ObjectID 53cf95f1-49be-463e-9856-77c2b2c3e4a0 -AddLicense -SkuID 84a661c4-e949-4bd2-a560-ed7766fcaf2b -DisabledPlans @("113feb6c-3fe4-4440-bddc-54d774bf0318", "932ad362-64a8-4783-9106-97849a1a30b9") -verbose
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.Group]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID,
            [parameter(Mandatory=$false)]
                [switch]$AddLicense,
            [parameter(Mandatory=$false)]
                [switch]$RemoveLicense,
            [parameter(mandatory=$false)]
                [guid[]]$DisabledPlans,
            [parameter(mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [guid]$SkuID
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject parameters - exiting"
            }
            if ($RemoveLicense -and $AddLicense) {
                throw "Please choose between AddLicense and RemoveLicense - exiting"
            }
            if (!($RemoveLicense) -and !($AddLicense)) {
                throw "Please choose between AddLicense and RemoveLicense, one parameter is mandatory - exiting"
            }
            if ($ObjectID -and $inputobject) {
                throw "Please choose between ObjectID or inputobject parameters - exiting"
            }
            $params = @{
                API = "groups"
                Method = "POST"
            }
            if ($inputobject.ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $inputobject.ObjectID
            } elseif ($ObjectID) {
                $ExistingGroup = Get-AzureADGroup -ObjectId $ObjectID
            }
            if ($ExistingGroup.ObjectID) {
                $params.add('APIParameter', $ExistingGroup.ObjectID + "/assignLicense")
            } else {
                throw "Azure AD Group not existing in directory"
            }
            if ($AddLicense) {
                $tmpbody = @{
                    addLicenses = @(
                        @{
                            skuId = $SkuID
                        }
                    )
                    removeLicenses = @()
                }
                if ($DisabledPlans) {
                    $tmpbody.addLicenses[0].add('disabledPlans',@($DisabledPlans))
                }
            }
            if ($RemoveLicense) {
                $tmpbody = @{
                    addLicenses = @()
                    removeLicenses = @($SkuID)
                }
            }
            $params.add('APIBody', ($tmpbody | ConvertTo-Json -Depth 99))
            write-verbose -Message $params.APIBody
            $tmpobj = Invoke-APIMSGraphBeta @params
            if ($tmpobj) {
                Get-AzureADGroupLicenseDetail -ObjectID $tmpobj.id
            }
        }
    }
    Function Get-AzureADUserLicenseAssignmentStates {
    <#
        .SYNOPSIS
        Get licensing assignment type (group or user) of a particular user
     
        .DESCRIPTION
        Get licensing assignment type (group or user) of a particular user. You can check if the license is assigned directly or inherited from a group membership.
         
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.User
        Microsoft.Open.AzureAD.Model.User generated previously with Get-AzureADUser cmdlet
     
        .PARAMETER ObjectID
        -ObjectID Guid
        Guid of an existing Azure AD User object
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get licensing assignment info for Azure AD user fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADUserLicenseAssignmentStates -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        Get licensing assignment info for Azure AD user fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureAdUser -ObjectID fb01091c-a9b2-4cd2-bbc9-130dfc91452a | Get-AzureADUserLicenseAssignmentStates
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.User]$inputobject,
            [parameter(Mandatory=$false)]
                [guid]$ObjectID
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($ObjectID) -and !($inputobject)) {
                throw "Please use ObjectID or inputobject parameter - exiting"
            }
            $params = @{
                API = "users"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $params.add('APIParameter',$inputobject.ObjectId + "?`$select=licenseAssignmentStates")
            } elseif ($ObjectID) {
                $params.add('APIParameter',$ObjectID.guid + "?`$select=licenseAssignmentStates")
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADServicePrincipalCustom {
    <#
        .SYNOPSIS
        Get Azure AD Service Principal by property and value
     
        .DESCRIPTION
        Get Azure AD Service Principal by property and value
         
        .PARAMETER Filter
        -Filter string
        Odata Filter query
     
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Service Principal
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get Azure AD service principal with the appid fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADServicePrincipalCustom -Filter "appid eq 'fb01091c-a9b2-4cd2-bbc9-130dfc91452a'"
     
        .EXAMPLE
        Get Azure AD service principal with the object id fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADServicePrincipalCustom -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$Filter,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [guid]$ObjectId
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($Filter) -and !($ObjectId)) {
                throw "Please use Filter or ObjectId parameter - exiting"
            }
            $params = @{
                API = "serviceprincipals"
                Method = "GET"
            }
            if ($ObjectId) {
            $params.add('APIParameter',$ObjectId.Guid)
            }
            if ($Filter) {
            $params.add('APIParameter',"?`$filter=$($Filter)")
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADAdministrativeUnitCustom {
    <#
        .SYNOPSIS
        Get Azure AD Administrative Unit properties by properties value or ID
     
        .DESCRIPTION
        Get Azure AD Administrative Unit properties by properties value or ID
         
        .PARAMETER Filter
        -Filter string
        Odata Filter query
     
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Administrative Unit
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Get Azure AD Administrative Unit with the displayname 'myadmin'
        C:\PS> Get-AzureADAdministrativeUnitCustom -Filter "displayname eq 'myadmin'"
     
        .EXAMPLE
        Get Azure AD Administrative Unit with the object id fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADAdministrativeUnitCustom -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        Get all Azure AD Administrative Units
        C:\PS> Get-AzureADAdministrativeUnitCustom -All
     
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$Filter,
            [parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [guid]$ObjectId,
            [parameter(Mandatory=$false)]
                [switch]$All
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($Filter) -and !($ObjectId) -and !($All)) {
                throw "Please use Filter or ObjectId parameter or All switch - exiting"
            }
            $params = @{
                API = "administrativeUnits"
                Method = "GET"
            }
            if ($ObjectId) {
                $params.add('APIParameter',$ObjectId.Guid)
            }
            if ($Filter) {
                $params.add('APIParameter',"?`$filter=$($Filter)")
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Add-AzureADAdministrativeUnitMemberCustom {
    <#
        .SYNOPSIS
        Get Azure AD Service Principal by property and value
     
        .DESCRIPTION
        Get Azure AD Service Principal by property and value
         
        .PARAMETER Filter
        -Filter string
        Odata Filter query
     
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Administrative Unit
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Add into an Azure AD admin unit (object id fb01091c-a9b2-4cd2-bbc9-130dfc91452a) a user (object id f8395a0b-3256-46b3-8dc8-db2e80a8ad52)
        C:\PS> Add-AzureADAdministrativeUnitMemberCustom -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a -RefObjectId f8395a0b-3256-46b3-8dc8-db2e80a8ad52 -RefObjectType users
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
            [ValidateNotNullOrEmpty()]
                [Guid]$ObjectId,
            [Parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [guid]$RefObjectId,
            [parameter(Mandatory=$true)]
            [validateSet("users","groups")]
                [string]$RefObjectType
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $body = [PSCustomObject]@{
                "@odata.id" = "https://graph.microsoft.com/beta/$($RefObjectType)/$($RefObjectId.Guid)"
            }
            $params = @{
                API = "administrativeUnits"
                Method = "POST"
                APIBody = (ConvertTo-Json -InputObject $body -Depth 100)
                APIParameter = "$($ObjectId.Guid)/members/`$ref"
            }
            write-verbose -Message "JSON Body : $(ConvertTo-Json -InputObject $body -Depth 100)"
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADUserAdministrativeUnitMemberOfCustom {
    <#
        .SYNOPSIS
        Get an Administrative Units of an Azure AD User account
     
        .DESCRIPTION
        Get an Administrative Units of an Azure AD User account
         
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the user account
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.User
         Microsoft.Open.AzureAD.Model.User object (for instance generated by Get-AzureADUser)
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        List Administrative Units of the Azure AD user account fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADUserAdministrativeUnitMemberOfCustom -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a
     
        .EXAMPLE
        List Administrative Units of the Azure AD user account my-admin@mydomain.tld
        C:\PS> get-azureaduser -ObjectId "my-admin@mydomain.tld" | Get-AzureADUserAdministrativeUnitMemberOfCustom
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.User]$inputobject,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [Guid]$ObjectId
        )
        process {
            if (!($inputobject) -and !($ObjectId)) {
                throw "Please inputobject or ObjectID Parameter - exiting"
            }
            Test-AzureADAccessTokenExpiration | out-null
            $params = @{
                API = "users"
                Method = "GET"
            }
            if ($inputobject.ObjectId) {
                $params.add('APIParameter',"$($inputobject.ObjectId)/memberOf/`$/Microsoft.Graph.AdministrativeUnit")
            } elseif ($ObjectId) {
                $params.add('APIParameter',"$($ObjectId.Guid)/memberOf/`$/Microsoft.Graph.AdministrativeUnit")
            } 
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Remove-AzureADAdministrativeUnitMemberCustom {
    <#
        .SYNOPSIS
        Remove a member of an Administrative Units
     
        .DESCRIPTION
        Remove a member of an Administrative Units
         
        .PARAMETER ObjectId
        -ObjectId guid
        GUID of the Administrative Unit
     
        .PARAMETER inputobject
        -inputobject Microsoft.Open.AzureAD.Model.AdministrativeUnit
         Microsoft.Open.AzureAD.Model.AdministrativeUnit object (for instance generated by Get-AzureADAdministrativeUnit)
     
        .PARAMETER RefObjectId
        -ObjectId RefObjectId
        GUID of the Administrative Unit member
                 
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        Remove Azure AD User account 50b147d8-411f-4359-a09a-e31a0d791900 from Administrative Unit fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Remove-AzureADAdministrativeUnitMemberCustom -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a -RefObjectId 50b147d8-411f-4359-a09a-e31a0d791900
     
        .EXAMPLE
        Remove Azure AD User account 50b147d8-411f-4359-a09a-e31a0d791900 from Administrative Unit fb01091c-a9b2-4cd2-bbc9-130dfc91452a
        C:\PS> Get-AzureADAdministrativeUnit -ObjectId fb01091c-a9b2-4cd2-bbc9-130dfc91452a | Remove-AzureADAdministrativeUnitMemberCustom -RefObjectId 50b147d8-411f-4359-a09a-e31a0d791900
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
                [Microsoft.Open.AzureAD.Model.AdministrativeUnit]$inputobject,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [Guid]$ObjectId,
            [parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [Guid]$RefObjectId    
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if (!($inputobject) -and !($ObjectId)) {
                throw "Please inputobject or ObjectID Parameter - exiting"
            }
            $params = @{
                API = "administrativeUnits"
                Method = "DELETE"
            }
            if ($inputobject.ObjectId) {
                $params.add('APIParameter',"$($inputobject.ObjectId)/members/$($RefObjectId.Guid)/`$ref")
            } elseif ($ObjectId) {
                $params.add('APIParameter',"$($ObjectId.Guid)/members/$($RefObjectId.Guid)/`$ref")
            } 
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Get-AzureADOrganizationCustom {
    <#
        .SYNOPSIS
        get all properties of an Azure AD organization
     
        .DESCRIPTION
        get all properties of an Azure AD organization
                     
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        get all properties of your current organization
        C:\PS> Get-AzureADOrganizationCustom
    #>

        [cmdletbinding()]
        Param ()
        process {
            Test-AzureADAccessTokenExpiration | out-null
            $params = @{
                API = "organization"
                Method = "GET"
            }
            Invoke-APIMSGraphBeta @params
        }
    }
    Function Update-AzureADOrganizationCustom {
    <#
        .SYNOPSIS
        update all properties of an Azure AD organization
     
        .DESCRIPTION
        update all properties of an Azure AD organization
     
        .PARAMETER marketingNotificationEmails
        -marketingNotificationEmails mailaddress
        e-mail address to be set for marketing notification
     
        .PARAMETER securityComplianceNotificationMails
        -securityComplianceNotificationMails mailaddress
        e-mail address to be set for security & compliance notification
     
        .PARAMETER technicalNotificationMails
        -technicalNotificationMails mailaddress
        e-mail address to be set for technical notification
     
        .PARAMETER privacyProfilemail
        -privacyProfilemail mailaddress
        e-mail address to be set for privacy notification
        this parameter must be used with privacyProfileurl parameter
     
        .PARAMETER privacyProfileurl
        -privacyProfileurl uri
        URL of the privacy information
        this parameter must be used with privacyProfilemail parameter
     
        .PARAMETER securityComplianceNotificationPhones
        -securityComplianceNotificationPhones string
        phone number to be set for security & compliance notification
                     
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
                 
        .EXAMPLE
        update privacy information
        C:\PS> Update-AzureADOrganizationCustom -privacyProfilemail test@test.com -privacyProfileurl http://www.google.com
     
        .EXAMPLE
        update marketing mail contact for notification
        C:\PS> Update-AzureADOrganizationCustom -marketingNotificationEmails lcuaad.xyz@outlook.com
    #>

        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [mailaddress]$marketingNotificationEmails,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [mailaddress]$securityComplianceNotificationMails,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$securityComplianceNotificationPhones,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [mailaddress]$technicalNotificationMails,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [mailaddress]$privacyProfilemail,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [uri]$privacyProfileurl
        )
        process {
            if (($privacyProfileurl -and !($privacyProfilemail)) -or (!($privacyProfileurl) -and $privacyProfilemail)) {
                throw "please use privacyProfilemail and privacyProfilemail together"
            }
            Test-AzureADAccessTokenExpiration | out-null
            $params = @{
                API = "organization"
                Method = "PATCH"
                APIParameter = "$($AADConnectInfo.TenantID)/"
            }
            $body = @{}
            if ($marketingNotificationEmails) {
                $body.add("marketingNotificationEmails",@($marketingNotificationEmails.Address))
            }
            if ($securityComplianceNotificationMails) {
                $body.add("securityComplianceNotificationMails",@($securityComplianceNotificationMails.Address))
            }
            if ($securityComplianceNotificationPhones) {
                $body.add("securityComplianceNotificationPhones",@($securityComplianceNotificationPhones))
            }
            if ($technicalNotificationMails) {
                $body.add("technicalNotificationMails",@($technicalNotificationMails.Address))
            }
            if ($privacyProfilemail -and $privacyProfileurl) {
                $body.add("privacyProfile",@{"contactEmail" = $privacyProfilemail.Address;"statementUrl" = $privacyProfileurl.AbsoluteUri})
            }
            if ($body) {
                $params.add("APIBody",(ConvertTo-Json -InputObject $body -Depth 100))
                write-verbose -Message "JSON Body : $(ConvertTo-Json -InputObject $body -Depth 100)"
                Invoke-APIMSGraphBeta @params
            }
        }
    }
    Function Get-AzureADOnPremisesProvisionningErrors {
    <#
        .SYNOPSIS
        Get all Azure AD Connect provisionning errors
     
        .DESCRIPTION
        Get all Azure AD Connect provisionning errors for groups, users, contacts object. Can replace old MSOnline function Get-MsolDirSyncProvisioningError
     
        .PARAMETER filterObjectType
        -filterObjectType string
        set an object type filter, value must be "users","groups","contacts" or "all" for all object type.
             
        .OUTPUTS
           TypeName : System.Management.Automation.PSCustomObject
             
        .EXAMPLE
        Get all Azure AD Connect provisionning errors for all object types
        C:\PS> Get-AzureADOnPremisesProvisionningErrors
     
        .EXAMPLE
        Get all Azure AD Connect provisionning errors for all contact object type
        C:\PS> Get-AzureADOnPremisesProvisionningErrors -filterObjectType "contacts"
    #>

        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [validateSet("users","groups","contacts","all")]
                [string]$filterObjectType = "all"
        )
        process {
            Test-AzureADAccessTokenExpiration | out-null
            if ($filterObjectType -ne "all") {
                    $params = @{
                        API = $filterObjectType
                        Method = "GET"
                        APIParameter = "?`$filter=onPremisesProvisioningErrors/any(i:i/category eq 'PropertyConflict')&select=onPremisesProvisioningErrors,id,displayname,mail"
                    }
                    $result = Invoke-APIMSGraphBeta @params
                    if ($result.value) {
                        $result
                    }
            } else {
                $filtersObjecttype = @("users","groups","contacts")
                foreach ($filtertype in $filtersObjecttype) {
                    $params = @{
                        API = $filtertype
                        Method = "GET"
                        APIParameter = "?`$filter=onPremisesProvisioningErrors/any(i:i/category eq 'PropertyConflict')&select=onPremisesProvisioningErrors,id,displayname,mail"
                    }
                    $result = Invoke-APIMSGraphBeta @params
                    if ($result.value) {
                        $result
                    }
                }
            }
        }
    }
    Function Invoke-APIMSGraphBeta {
        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [validateSet("users","me","administrativeUnits","serviceprincipals","groups","organization","contacts")]
                [string]$API,
            [parameter(Mandatory=$true)]
            [validateSet("GET","POST","PUT","PATCH","DELETE")]
                [string]$Method,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$APIParameter,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [string]$APIBody,
            [Parameter(Mandatory=$false)]
            [ValidateNotNullOrEmpty()]
                [uri]$Paging
        )
        process {
            $authHeader = @{
                'Content-Type' = "application/json"
                'Authorization' = "Bearer $($global:AADConnectInfo.AccessToken)"
                'ExpiresOn' = $global:AADConnectInfo.TokenExpiresOn
                'x-ms-client-request-id' = [guid]::NewGuid()
                'x-ms-correlation-id'    = [guid]::NewGuid()
            }
            if (($paging.AbsoluteUri -like "*skiptoken=*") -or ($paging.AbsoluteUri -like "*deltatoken=*")) {
                $uri = $paging.AbsoluteUri
                write-verbose -Message $uri
            } else {
                $uri = "https://graph.microsoft.com/beta/$($API)"
                if ($APIParameter) {
                    $uri = $uri + "/" + $APIParameter
                }
            }
            write-verbose -message "$($Method) to $($uri)"
            $params = @{ 
                UseBasicParsing = $true
                headers = $authHeader
                Uri = $uri
                Method = $Method
            }
            if ($Method -ne "GET") {
                $params.add("Body",$APIBody)
            }
            try {
                $response = Invoke-WebRequest @params
            } catch {
                $ex = $_.Exception
                $errorResponse = $ex.Response.GetResponseStream()
                $reader = New-Object System.IO.StreamReader($errorResponse)
                $reader.BaseStream.Position = 0
                $reader.DiscardBufferedData()
                $responseBody = $reader.ReadToEnd();
                write-verbose -message "Response content:`n$responseBody"
                $responseerror = ConvertFrom-Json $responseBody
                write-error -message "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
            }
            if ($response.Content) {
                $result = ConvertFrom-Json $response.Content
                write-verbose -Message $response.Content
                if ($result.value) {
                    $result.value
                } else {
                    $result
                }
                if ($result.'@odata.nextLink') {
                    Invoke-APIMSGraphBetaPaging -Paging $result.'@odata.nextLink'
                }
            } elseif ($responseerror ) {
                $responseerror
            } else {
                Write-verbose -message "response is null"
            }
        }
    }
    Function Invoke-APIMSGraphBetaPaging {
        [cmdletbinding()]
        Param (
            [Parameter(Mandatory=$true)]
            [ValidateNotNullOrEmpty()]
                [uri]$Paging
        )
        process {
            $script:authHeader = @{
                'Content-Type' = "application/json"
                'Authorization' = "Bearer $($global:AADConnectInfo.AccessToken)"
                'ExpiresOn' = $global:AADConnectInfo.TokenExpiresOn
                'x-ms-client-request-id' = [guid]::NewGuid()
                'x-ms-correlation-id'    = [guid]::NewGuid()
            }
            $script:uri = $paging.AbsoluteUri
            write-verbose -Message "Paging : $($script:uri)"
            $script:ExitPaging = $false
            while ($script:ExitPaging -ne $true) {
                if (($script:uri -like "*skiptoken=*") -or ($script:uri -like "*deltatoken=*")) {
                    write-verbose -Message $script:uri
                    $params = @{ 
                        UseBasicParsing = $true
                        headers = $script:authHeader
                        Uri = $script:uri
                        Method = "GET"
                    }
                    try {
                        $response = Invoke-WebRequest @params
                    } catch {
                        $ex = $_.Exception
                        $errorResponse = $ex.Response.GetResponseStream()
                        $reader = New-Object System.IO.StreamReader($errorResponse)
                        $reader.BaseStream.Position = 0
                        $reader.DiscardBufferedData()
                        $responseBody = $reader.ReadToEnd();
                        write-verbose -message "Response content:`n$responseBody"
                        $responseerror = ConvertFrom-Json $responseBody
                        write-error -message "Request to $script:uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
                    }
                    if ($response.content) {
                        $result = ConvertFrom-Json $response.Content
                        write-verbose -Message $response.Content
                        if ($result.value) {
                            $result.value
                        } else {
                            $result
                        }
                        if ($result.'@odata.deltaLink') { 
                            [PSCustomObject]@{
                                deltaLink = $result.'@odata.deltaLink'
                            }
                        } 
                        if ($result.'@odata.nextLink') {
                            $script:uri = $result.'@odata.nextLink'
                        } else {
                            $script:ExitPaging = $true
                        }
                    } elseif ($responseerror) {
                        $responseerror
                    } else {
                        Write-verbose -message "response is null"
                    }
                } else {
                    $script:ExitPaging = $true
                }
            }
        }
    }
    Function Test-ADModule {
        [cmdletbinding()]
        Param (
            [parameter(Mandatory=$false)]
            [switch]$AzureAD,
            [parameter(Mandatory=$false)]
            [switch]$AD,
            [parameter(Mandatory=$false)]
            [switch]$MSOnline
        )
        Process {
            if ($AzureAD.IsPresent) {
                try {
                    $AadModule = get-module -Name AzureADPreview
                    if (!($AadModule)) {
                        import-module -name AzureADPreview
                        $AadModule = get-module -Name AzureADPreview
                    }
                } catch {
                    throw "AzureADPreview module is missing, please install this module using 'install-module AzureADPreview' - exiting"
                }
                $AadModule
            }
            if ($AD.IsPresent) {
                try {
                    $AdModule = get-module -Name ActiveDirectory
                    if (!($AdModule)) {
                        import-module -name ActiveDirectory
                        $AdModule = get-module -Name ActiveDirectory
                    }
                } catch {
                    throw "ActiveDirectory module is missing, please install this module using 'Add-WindowsCapability -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 -Online' or 'Add-WindowsFeature -Name RSAT-AD-Tools' - exiting"
                }
                $AdModule
            }
            if ($MSOnline.IsPresent) {
                try {
                    $AdModule = get-module -Name MSOnline
                    if (!($AdModule)) {
                        import-module -name MSOnline
                        $MSOnlineModule = get-module -Name MSOnline
                    }
                } catch {
                    throw "MSOnline module is missing, please install this module using 'install-module MSOnline' - exiting"
                }
                $MSOnlineModule
            }
        }
    }
    Function Test-AzureADAccesToken {
        [cmdletbinding()]
        Param ()
        Process {
            if(!($global:AADConnectInfo.AccessToken)) {
                throw "Not able to find a valid Azure AD Access Token in cache, please use Get-AzureADAccessToken first - exiting"
            }
        }
    }
    Function Test-AzureADAccessTokenExpiration {
        [cmdletbinding()]
        Param ()
        process {
            Test-AzureADAccesToken
            if ((get-date).ToUniversalTime() -gt $AADConnectInfo.TokenExpiresOn.DateTime.AddMinutes(-15)) {
                $remainingtime = $AADConnectInfo.TokenExpiresOn.DateTime.AddMinutes(-15) - (get-date).ToUniversalTime()
                write-warning -Message "your token is about to expire in $($remainingtime.Minutes.tostring()) minutes."
                return $true
            } else {
                return $false
            }
        }
    }
    
    New-Alias -Name Get-AzureADUserAllInfo -Value Get-AzureADUserCustom
    
    Export-ModuleMember -Function Get-AzureADTenantInfo, Get-AzureADMyInfo, Get-AzureADAccessToken, Connect-AzureADFromAccessToken, Clear-AzureADAccessToken, 
                                    Set-AzureADProxy, Test-ADModule, Sync-ADOUtoAzureADAdministrativeUnit, Get-AzureADUserCustom, Test-AzureADAccesToken,
                                    Sync-ADUsertoAzureADAdministrativeUnitMember,Set-AzureADAdministrativeUnitAdminRole, Get-AzureADAdministrativeUnitAllMembers, Connect-MSOnlineFromAccessToken,
                                    Get-AzureADConnectCloudProvisionningServiceSyncSchema, Update-AzureADConnectCloudProvisionningServiceSyncSchema,
                                    Get-AzureADConnectCloudProvisionningServiceSyncDefaultSchema, New-AzureADAdministrativeUnitCustom, Get-AzureADAdministrativeUnitHidden,
                                    New-AzureADObjectDeltaView, Get-AzureADObjectDeltaView, 
                                    Get-AzureADGroupMembersWithLicenseErrors, Get-AzureADGroupLicenseDetail, Set-AzureADGroupLicense, Get-AzureADUserLicenseAssignmentStates, 
                                    Get-AzureADDynamicGroup, New-AzureADDynamicGroup, Remove-AzureADDynamicGroup, Set-AzureADDynamicGroup, Test-AzureADUserForGroupDynamicMembership,
                                    Get-AzureADServicePrincipalCustom, Get-AzureADAdministrativeUnitCustom, Add-AzureADAdministrativeUnitMemberCustom, Test-AzureADAccessTokenExpiration,
                                    Watch-AzureADAccessToken, Get-AzureADUserAdministrativeUnitMemberOfCustom, Remove-AzureADAdministrativeUnitMemberCustom,
                                    Get-AzureADOrganizationCustom, Update-AzureADOrganizationCustom, Get-AzureADOnPremisesProvisionningErrors,
                                    Invoke-APIMSGraphBetaPaging, Invoke-APIMSGraphBeta,
                                    New-AzureADMSGroupCustom, Set-AzureADMSGroupCustom
    Export-ModuleMember -Alias Get-AzureADUserAllInfo