Groups.ps1

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
using namespace Microsoft.Graph.PowerShell.Models
using namespace System.Management.Automation

function Get-GraphGroupList         {
    <#
      .Synopsis
        Gets a list of Groups in Microsoft Graph.
      .Description
        The list of groups returned can be filtered by name (the beginning of the displayname and mail
        address are checked) or with a custom filter string, or it can be sorted, or specific fields can
        be selected. However there is a limitation in the graph API which prevent these being combined.
        Requires consent to use the Group.Read.All scope.
      .Example
        >Get-GraphGroupList | Format-Table -Autosize Displayname, SecurityEnabled, Mailenabled, Mail, ID
        Displays a table of groups in the current tennant
      .Example
        >(Get-GraphGroupList -Name consult | Get-GraphTeam -Site).weburl
        Gets any group whose name begins "Consult" , finds its sharepoint site, and returns the site's URL
    #>

    [Cmdletbinding(DefaultparameterSetName="None")]
    [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphGroup])]
    param   (
        #if specified limits the groups returned to those with names begining...
        [Parameter(Mandatory=$true, parameterSetName='FilterByName', Position=0)]
        [string]$Name,
        #Field(s) to select: ID and displayname are always included;
        #The following are only available when getting a single group:
        #'allowExternalSenders','autoSubscribeNewMembers','isSubscribedByMail' 'unseenCount',
        [ValidateSet( 'acceptedSenders', 'allowExternalSenders', 'appRoleAssignments', 'assignedLabels', 'assignedLicenses',
                'autoSubscribeNewMembers', 'calendar', 'calendarView', 'classification', 'conversations', 'createdDateTime',
                'createdOnBehalfOf', 'deletedDateTime', 'description', 'displayName', 'drive', 'drives', 'events',
                'expirationDateTime', 'extensions', 'groupLifecyclePolicies', 'groupTypes', 'hasMembersWithLicenseErrors',
                'hideFromAddressLists', 'hideFromOutlookClients', 'id', 'isArchived', 'isSubscribedByMail',
                'licenseProcessingState', 'mail', 'mailEnabled', 'mailNickname', 'memberOf', 'members', 'membershipRule',
                'membershipRuleProcessingState', 'membersWithLicenseErrors', 'onenote', 'onPremisesDomainName',
                'onPremisesLastSyncDateTime', 'onPremisesNetBiosName', 'onPremisesProvisioningErrors',
                'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'owners',
                'permissionGrants', 'photo', 'photos', 'planner', 'preferredDataLocation', 'preferredLanguage',
                'proxyAddresses', 'rejectedSenders', 'renewedDateTime', 'securityEnabled', 'securityIdentifier', 'settings',
                'sites', 'team', 'theme', 'threads', 'transitiveMemberOf', 'transitiveMembers', 'unseenCount', 'visibility')]
        [Parameter(Mandatory=$true, parameterSetName='SelectFields')]
        [string[]]$Select,
        #An oData order by string
        [Parameter(Mandatory=$true, parameterSetName='OrderBy')]
        [ValidateSet('allowExternalSenders', 'assignedLabels', 'assignedLicenses', 'autoSubscribeNewMembers', 'classification',
                'createdDateTime', 'deletedDateTime', 'description', 'displayName', 'expirationDateTime', 'groupTypes',
                'hasMembersWithLicenseErrors', 'hideFromAddressLists', 'hideFromOutlookClients', 'id', 'isArchived',
                'isSubscribedByMail', 'licenseProcessingState', 'mail', 'mailEnabled', 'mailNickname', 'membershipRule',
                'membershipRuleProcessingState', 'onPremisesDomainName', 'onPremisesLastSyncDateTime', 'onPremisesNetBiosName',
                'onPremisesProvisioningErrors', 'onPremisesSamAccountName', 'onPremisesSecurityIdentifier',
                'onPremisesSyncEnabled', 'preferredDataLocation', 'preferredLanguage', 'proxyAddresses', 'renewedDateTime',
                'securityEnabled', 'securityIdentifier', 'theme', 'unseenCount', 'visibility')]
        [string]$OrderBy,

        [Parameter(parameterSetName='Sort')]
        [Switch]$Descending,
        #An oData filter string; there is a graph limitation that you can't filter by description or Visibility.
        [Parameter(Mandatory=$true, parameterSetName='FilterByString')]
        [string]$Filter
    )
    process {
        #xxxx to do: investigate "groupTypes/any(c: c eq 'Unified')" -filter "groupTypes/any(x: x eq 'DynamicMembership')"
        # check access to scopes Group.Read.All

        if     ($Select)  {
            if ("id" -notin $select)          {$select += 'id'}
            if ("displayName" -notin $select) {$select += 'displayName'}
            $uri  =  $GraphUri +  '/Groups/?$select='  + ($Select -join ',')
        }
        elseif ($Filter)  {$uri =  $GraphUri +  '/Groups/?$Filter='  + $Filter }
        elseif ($Name)    {
            #for once we don't need to fix case.If * is specified , remove it.
            if ($Name -match '\*') {$Name = $Name -replace "\*",""}
                $uri = ( $GraphUri +  "/Groups/?&`$filter=startswith(displayName,'{0}') or startswith(mail,'{0}')" -f $Name)
        }
        else   {$uri =  $GraphUri +  '/Groups/?$OrderBy=displayname' }
        Write-Progress -Activity "Finding Groups"
        Invoke-GraphRequest -Uri $uri -AllValues -ExcludeProperty 'creationOptions' -AsType ([MicrosoftGraphGroup])
        Write-Progress -Activity "Finding Groups" -Completed
    }
}

function Get-GraphGroup             {
    <#
      .Synopsis
        Gets information about a Group and any associated Office 365 Team
      .Description
        Takes a Group/Team ID or object as a parameter and gets information about it.
        Apps, Calendar, Channels, Drive, Members or Planners can be requested.
        Depending on which aspect of the group are queried, may need access to the following
        Scopes Group.Read.All, Files.Read, Sites.Read.All, Notes.Create, Notes.Read,
      .Example
        >Get-GraphUser -teams | Get-GraphTeam -Plans | select -last 1 | Get-GraphPlan -FullTasks | ft PlanTitle,Bucketname,Title,DueDateTime,PercentComplete,Assignees
         Gets the current user's Teams, and gets the plans for each;
         Note that because we are refering to "Teams" the command is calling using its alias
         of Get-GraphTeam. The last plan is selected and details of the plan are fetched,
         showing the result as a table.
      .Example
        >(Get-GraphGroup -Site).lists | where name -match document
        If no Group/Team is provided the command gets those associated with the
        current user; it this case it returns their associated site(s).
        Site objects include a lists property, which holds a collection of lists
        this command will fiter the lists down to those where name matches "document"
      .Example
        >Get-GraphGroup -Drive | Get-GraphDrive -Subfolders | Select name, weburl, id,@{n="drive";e={$_.parentReference.driveId}}
        As with the previous example gets this command gets Groups/Teams for current user,
        in this case the command returns their associated drive(s)
        It is possible to refer to the drive's root property, and the root's children property
        which contains files and folder objects, amd filter to objects with a folder property but
        for ease of reading this pipeline passes the drive to Get-GraphDrive to get subfolders.
        It then returns the name, WebURl and the item ID and Drive ID needed to access each folder.
      .Example
        >Get-GraphGroup 'Consultants' -Drive | Set-GraphHomeDrive
        Sets the drive for the consultants group to thebe the default graph drive for the PowerShell session.
     .Example
        >Get-GraphGroup -Notebooks | select -ExpandProperty sections | where "Displayname" -eq "General_Notes"
        Again gets Groups/Teams for the current user and returns their associated notebooks(s)
        Notebook objects include a Sections property, which holds a collection of OneNote sections in the notebook;
        This command gets returns any section in a team notebook which has the name "General_Notes"
      .Example
        > Get-GraphTeam -threads | where LastDeliveredDateTime -gt [datetime]::Now.AddDays(-7)
        Gets the teams conversation threads which have been updated in the last 7 days.
    #>

    [Cmdletbinding(DefaultparameterSetName="None")]
    [Alias("Get-GraphTeam","ggg")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '',  Justification='Write-warning could be used, but the is informational non-output.')]
    param   (
        #The name of a team.
        #One more Team IDs or team objects containing and ID. If omitted the current user's teams will be used.
        [Parameter(ValueFromPipeline=$true, Position=0)]
        [Alias("Team","Group")]
        [ArgumentCompleter([GroupCompleter])]
        $ID ,
        #If specified returns the teams Apps
        [Parameter(parameterSetName='Apps')]
        [switch]$Apps,
        #If specified gets the team's Calendar (a team only has one)
        [Parameter(Mandatory=$true, parameterSetName='Calendar')]
        [switch]$Calendar,
        #If specified gets the team's channels
        [Parameter(parameterSetName='Channels')]
        [switch]$Channels,
        #If Specified, retrun team's conversations (usually better to use threads)
        [Parameter(Mandatory=$true, parameterSetName='Conversations' )]
        [switch]$Conversations,
        #If specified gets the Team's OneDrive to see contents of the root of the drive you can refer to the drives .root.children property
        [Parameter(Mandatory=$true, parameterSetName='Drive')]
        [switch]$Drive,
        #If specified returns the members of the team
        [Parameter(Mandatory=$true, parameterSetName='Members')]
        [switch]$Members,
        #If specified returns the transitive members of the team
        [Parameter(Mandatory=$true, parameterSetName='TransitiveMembers')]
        [switch]$TransitiveMembers,
        #If specified returns the groups this group is directly a member of
        [Parameter(Mandatory=$true, parameterSetName='Memberof')]
        [switch]$MemberOf,
        #If specified returns the groups this group is nested into transitively
        [Parameter(Mandatory=$true, parameterSetName='TransitiveMemberof')]
        [switch]$TransitiveMemberOf,
        #If specified returns the Owners of the team
        [Parameter(Mandatory=$true, parameterSetName='Owners')]
        [switch]$Owners,
        #If specified returns the team's notebook(s)
        [Parameter(Mandatory=$true, parameterSetName='Notebooks')]
        [switch]$Notebooks,
        #if Specified, returns the teams Planners.
        [Parameter(Mandatory=$true, parameterSetName='Planners')]
        [switch]$Plans,
        #If Specified, retrun team's threads
        [Parameter(Mandatory=$true, parameterSetName='Threads' )]
        [switch]$Threads,
        #if Specified, returns the teams site.
        [Parameter(Mandatory=$true, parameterSetName='Site')]
        [switch]$Site,
        #limits searches for appsby name.
        [Parameter(parameterSetName='Apps')]
        [String]$AppName,
        #limits searches for channels by name. Other's cant be filtered by name ... perhaps notebooks can but a group only has one.
        [Parameter(parameterSetName='Channels')]
        [String]$ChannelName,
         #Field(s) to select: ID and displayname are always included
        #The following are available when getting a single group:
        [ValidateSet('acceptedSenders', 'allowExternalSenders', 'appRoleAssignments', 'assignedLabels', 'assignedLicenses',
                'autoSubscribeNewMembers', 'calendar', 'calendarView', 'classification', 'conversations', 'createdDateTime',
                'createdOnBehalfOf', 'deletedDateTime', 'description', 'displayName', 'drive', 'drives', 'events',
                'expirationDateTime', 'extensions', 'groupLifecyclePolicies', 'groupTypes', 'hasMembersWithLicenseErrors',
                'hideFromAddressLists', 'hideFromOutlookClients', 'id', 'isArchived', 'isSubscribedByMail',
                'licenseProcessingState', 'mail', 'mailEnabled', 'mailNickname', 'memberOf', 'members', 'membershipRule',
                'membershipRuleProcessingState', 'membersWithLicenseErrors', 'onenote', 'onPremisesDomainName',
                'onPremisesLastSyncDateTime', 'onPremisesNetBiosName', 'onPremisesProvisioningErrors',
                'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'owners',
                'permissionGrants', 'photo', 'photos', 'planner', 'preferredDataLocation', 'preferredLanguage', 'proxyAddresses',
                'rejectedSenders', 'renewedDateTime', 'securityEnabled', 'securityIdentifier', 'settings', 'sites', 'team',
                'theme', 'threads', 'transitiveMemberOf', 'transitiveMembers', 'unseenCount', 'visibility')]
        [Parameter(Mandatory=$true, parameterSetName='SelectFields')]
        [string[]]$Select,
        [Parameter(Mandatory=$true, parameterSetName='BareGroups')]
        [switch]$NoTeamInfo
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        #xxxx toDo check scopes - Scopes Group.Read.All, Files.Read, Sites.Read.All, Notes.Create, Notes.Read, depending on params passed.
        # if we didn't get passed a group but we did get asked for something about a group or groups then get the current user's groups,
        if      ($PSBoundParameters.Keys.Where({$_ -notin [cmdlet]::CommonParameters}) -and -not $ID)  {
                       $ID = Get-GraphUser -Current -Groups
        }
        # If we got nothing return the list,
        elseif  (-not  $ID) { Get-GraphGroupList ; return  }
        # if we got a single string that looks like a name (not a GUID) resolve it.
        elseif  ($ID -is [string] -and  $ID -notmatch $guidregex)   {
                       $ID = Get-GraphGroupList -Name $id
        }
        # We'll loop through an array and (or single object) with either GUIDs or objects.
        $usersAndGroups = @()
        foreach ($i in $ID) {
            <# not all teams have team set in resource procisioning options
                if ($i.ResourceProvisioningOptions -is [array] -and
                 $i.ResourceProvisioningOptions -notcontains "Team" -and
                ($Channels -or $ChannelName -or $Apps)) {
                Write-Verbose "$($i.DisplayName) is a group but not a team"
                continue
            }#>

            if  ($i -is [string] -and
                 $i -notmatch $guidregex) {$i = Get-GraphGroupList -Name $i}
            if  ($i.DisplayName)          {$displayname       = $i.DisplayName}
            else                          {$displayname       = $i            }
            if  ($i.id)                   {$groupid = $teamid = $i.id         }
            else                          {$groupid = $teamid = $i            }
            $groupURI = "$GraphUri/groups/$groupid"
            $teamURI  = "$GraphUri/teams/$teamid"
            try   {
                #For each of the switches get the data from /groups{id}/whatever or /teams/{id}.whatever
                #Add a type to PS Type names so we can format it, and add any properties we expect to want later.
                Write-Progress -Activity 'Getting Group Information' -CurrentOperation $displayname
                if     ($Site)               {
                    $uri = ("$groupURI/sites/root?expand=drives,sites,lists(expand=columns,contenttypes,drive)")
                    $result  =  Invoke-GraphRequest -Uri $uri -ExcludeProperty 'sites@odata.context', '@odata.context', 'drives@odata.context', 'lists@odata.context' -AsType ([MicrosoftGraphSite]) |
                            Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    foreach ($siteObj in $result) {
                        foreach ($l in $siteObj.lists) {
                            Add-Member -InputObject $l -NotePropertyName SiteID    -NotePropertyValue  $siteObj.id
                            Add-Member -InputObject $l -NotePropertyName ParentUrl -NotePropertyValue  $siteObj.weburl
                        }
                        $siteobj
                    }
                    continue
                }
                elseif ($Calendar)           {
                    Invoke-GraphRequest -Uri  "$groupURI/calendar" -ExcludeProperty "@odata.context" -AsType ([MicrosoftGraphCalendar]) |
                        Add-Member -PassThru -NotePropertyName GroupID      -NotePropertyValue $groupid   |
                        Add-Member -PassThru -NotePropertyName CalendarPath -NotePropertyValue "groups/$groupid/Calendar" |
                        Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    continue
                }
                elseif ($Drive)              {
                    $uri = ("$groupURI/drive" + '?$expand=root($expand=children)' )
                    Invoke-GraphRequest  -Uri $uri -ExcludeProperty "@odata.context", "root@odata.context" -AsType ([MicrosoftGraphDrive]) |
                        Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    continue
                }
                elseif ($Members)            { #can do group ?$expand=Memebers, the others don't expand
                    $usersAndGroups += Invoke-GraphRequest  -Uri  "$groupURI/members"  -AllValues |
                        ForEach-Object {$_['GroupName'] =  $displayname ; $_ }
                }
                elseif ($TransitiveMembers)  {
                    $usersAndGroups += Invoke-GraphRequest  -Uri  "$groupURI/TransitiveMembers"  -AllValues |
                        ForEach-Object {$_['GroupName'] =  $displayname ; $_ }
                }
                elseif ($MemberOf)          { #can do group ?$expand=Memebers, the others don't expand
                    $usersAndGroups += Invoke-GraphRequest  -Uri  "$groupURI/memberof"  -AllValues |
                        ForEach-Object {$_['GroupName'] =  $displayname ; $_ }
                }
                elseif ($TransitiveMemberOf)  {
                    $usersAndGroups += Invoke-GraphRequest  -Uri  "$groupURI/TransitiveMemberof"  -AllValues |
                        ForEach-Object {$_['GroupName'] =  $displayname ; $_ }
                }
                elseif ($Owners)             {
                    $usersqAndGroups +=  Invoke-GraphRequest  -Uri  "$groupURI/Owners" -AllValues|
                        ForEach-Object {$_['GroupName'] =  $displayname ; $_ }
                }
                elseif ($Notebooks)          {
                    #if groups can have more than one book , then add if name ... uri = blah + "?`$expand=sections&`$filter=startswith(tolower(displayname),'$name')"
                    $uri = $groupURI + '/onenote/notebooks?$expand=sections'
                    $response = Invoke-GraphRequest  -Uri $uri -ValueOnly -ExcludeProperty 'sections@odata.context'  -AsType ([MicrosoftGraphNotebook]) |
                        Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    foreach ($bookobj in $response) {
                        #Section fetched this way won't have parentNotebook, so make sure it is available when needed
                        foreach ($s in $bookobj.sections) {$s.ParentNotebook = $bookobj}
                        $bookobj
                    }
                    continue
                }
                elseIf ($Plans)              {
                    #would like to have expand details here but it only works with a single plan.
                    try {
                        $result  = Invoke-GraphRequest  -Uri  "$groupURI/planner/plans"  -AllValues -ExcludeProperty  "@odata.etag" -AsType ([MicrosoftGraphPlannerPlan]) |
                            Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    }
                    catch             { Write-Warning "Could not get plans for $($ID.DisplayName)." ;   continue}
                    if (-not $result) { Write-Host "The team $($ID.DisplayName) has not created any plans" ;   continue}
                    $dirObjectsHash = @{}
                    if ($i.displayName) {$dirObjectsHash[$teamId] = $i.displayName}
                    @() + $result.owner + $result.createdby.user.id  |ForEach-Object  {
                        if (-not $dirObjectsHash[$_]) {
                            $dirObjectsHash[$_] = (Invoke-GraphRequest  -Uri "$GraphUri/directoryobjects/$_").displayname
                        }
                    }
                    foreach ($r in $result) {
                        Add-Member -PassThru  -InputObject $r  -NotePropertyName OwnerName   -NotePropertyValue $dirObjectsHash[$r.owner] |
                        Add-Member -PassThru                   -NotePropertyName CreatorName -NotePropertyValue $dirObjectsHash[$r.createdBy.user.id]
                    }
                }
                elseif ($Threads)            {
                    Invoke-GraphRequest  -Uri  "$groupURI/threads"  -AllValues -AsType ([MicrosoftGraphConversationThread]) |
                        Add-Member -PassThru -NotePropertyName Group       -NotePropertyValue $groupid  |
                        Add-Member -PassThru -NotePropertyName GroupName   -NotePropertyValue $displayname
                }
                elseif ($Conversations)      {
                     $result = Invoke-GraphRequest  -Uri ($groupURI + '/conversations?$expand=Threads')  -AllValues -As ([MicrosoftGraphConversation]) |
                        Add-Member -PassThru -NotePropertyName Group        -NotePropertyValue $groupid  |
                        Add-Member -PassThru -NotePropertyName GroupName    -NotePropertyValue $displayname
                    foreach ($convobj in $result) {
                        foreach ($t in $convObj.threads) {
                            Add-Member -InputObject $t -NotePropertyName Group      -NotePropertyValue $groupid  |
                            Add-Member -InputObject $t -NotePropertyName GroupName  -NotePropertyValue $displayname
                        }
                        $convObj
                    }
                    continue
                }
                elseif ($Channels -or
                        $ChannelName)       {
                    if ($ChannelName)   { $uri =  "$teamURI/channels?`$filter=startswith(tolower(displayname), '$($ChannelName.ToLower())')"}
                    else                { $uri =  "$teamURI/channels"}
                    Invoke-GraphRequest  -Uri $uri -ValueOnly -As ([MicrosoftGraphChannel]) |
                        Add-Member -PassThru -NotePropertyName Team      -NotePropertyValue $teamid |
                        Add-Member -PassThru -NotePropertyName TeamName  -NotePropertyValue $displayname
                }
                elseif ($Apps -or
                        $AppName)           {
                    $uri = $teamURI + '/installedApps?$expand=teamsAppDefinition'
                    if ($AppName) { $uri = $URI + '&$filter=' +
                                    "startswith(tolower(teamsappdefinition/displayname),'$($AppName.ToLower())')"
                    }
                    Invoke-GraphRequest  -Uri $uri -ValueOnly  -As ([MicrosoftGraphTeamsAppDefinition]) |
                        Add-Member -PassThru -NotePropertyName Team      -NotePropertyValue $teamid |
                        Add-Member -PassThru -NotePropertyName TeamName  -NotePropertyValue $displayname
                }
                elseif ($Select)             {
                    $SelectList = (@('id','displayName') + $Select ) -join','
                    Invoke-GraphRequest  -Uri ($groupuri + '?$Select=' + $SelectList ) -ExcludeProperty '@odata.context' -As ([MicrosoftGraphGroup])
                }
                else                         {
                    $g =  Invoke-GraphRequest  -Uri "$groupuri`?`$expand=members"  -ExcludeProperty '@odata.context','creationOptions' -As ([MicrosoftGraphGroup])
                    # consider adding $MyInvocation.InvocationName -ne 'Get-GraphTeam'
                    if ($g.resourceProvisioningOptions -notcontains 'Team' -or $NoTeamInfo) { $g }
                    else {
                        $t = Invoke-GraphRequest  -Uri  "$teamURI"                  -ExcludeProperty '@odata.context' -As ([MicrosoftGraphTeam])
                        $t.members = $g.Members
                        $t
                    }
                }
            }
            catch {
                if ($_.exception -match"Forbidden") {
                    Write-warning -Message "Server returned a 403 (Forbidden) error; you must be a memeber of the team $($t.displayname) to view some things [admin does not give access]. "
                }
                if ($_.exception.response.statuscode.value__ -eq 404) {
                    Write-Verbose -Message "GET-GROUP: Nothing found the group $displayname"
                }
                else {throw $_  }
            }
        }
        foreach( $g in $usersAndGroups.where({$_.'@odata.type' -match 'group$'})) {
            $displayname = $g.GroupName
            [void]$g.Remove('GroupName')
            [void]$g.remove('@odata.type')
            [void]$g.remove('@odata.context')
            [void]$g.remove('creationOptions')
            New-Object -Property  $g -TypeName MicrosoftGraphGroup |
                Add-Member -PassThru -NotePropertyName GroupName  -NotePropertyValue $displayname
        }
        foreach( $u in $usersAndGroups.where({$_.'@odata.type' -match 'user$'})) {
            $displayname = $u.GroupName
            [void]$u.Remove('GroupName')
            [void]$u.Remove('@odata.type')
            [void]$u.Remove('@odata.context')
            New-Object -Property $u -TypeName MicrosoftGraphUser |
                Add-Member -PassThru -NotePropertyName GroupName  -NotePropertyValue $displayname
        }
    }
    end     {
        Write-Progress -Activity 'Getting Group/Team information' -Completed
    }
}

function New-GraphGroup             {
    <#
      .Synopsis
        Adds a new group/team
      .Description
        Every team is also a group, but not every group is team enabled.
        This Command has an alias of New-GraphTeam so you call it as team or group
        By default it creates the group as a team UNLESS you specify -NoTeam.
        A non-Teams enabled group can be teams enabled with Set-GraphGroup -EnableTeam
        Creating and modifying groups requires consent to use the Group.ReadWrite.All scope
    #>

    [Cmdletbinding(SupportsShouldprocess=$true,DefaultParameterSetName="None")]
    [outputtype([Microsoft.Graph.PowerShell.Models.MicrosoftGraphGroup])]
    [Alias("New-GraphTeam")]
    param   (
        #The name of the Group / Team
        [Parameter(Mandatory=$true, Position=0)]
        [string]$Name,

        #Unless specified, groups will be mail enabled "unfied" / Microsoft365 groups
        #The Graph API doesn't allow mail-enabled & security-enabled, or mail-disabled & unified
        #Only unified groups can be made into teams. Unified groups can only contain users,
        #Security groups can contain other security principals
        [parameter(ParameterSetName='Security',Mandatory=$true)]
        [Switch]$AsSecurity,

        #If specified allows Azure AD roles can be assigned to the group. This forces visibility to be private, and can't be changed.
        [parameter(ParameterSetName='Security')]
        [Switch]$AsAssignableToRole,

        #New-GraphGroup only enables teams functonality if -AsTeam is specified. Calling as New-GraphTeam defaults AsTeam to true
        [parameter(ParameterSetName='Team',Mandatory=$true)]
        [Switch]$AsTeam,

        #A description for the group
        [string]$Description,

        #The group/team's mail nickname
        [string]$MailNickName,

        #The visibility of the group, Public by default, it can be 'private' or 'hidden membership'
        [ValidateSet('private', 'public', 'hiddenmembership')]
        [string]$Visibility = 'public',

        #Ordinary Members of the group - assumed to be users, given by their User Principal Name or ID or as objects
        $Members,

        #Owners of the group - assumed to be users, given by their User Principal Name or ID or as objects
        [parameter(ParameterSetName='Owners')]
        [parameter(ParameterSetName='Security')]
        $Owners,

        #if specified group will be added without prompting
        [Switch]$Force
    )
    ContextHas -WorkOrSchoolAccount -BreakIfNot

    if (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=displayname eq '$Name'" -ValueOnly) {
        throw "There is already a group with the display name '$Name'." ; return
    }
    #Server-side is case-sensitive for [most] JSON so make sure hashtable names and constants have the right case!
    if (-not $MailNickName) {$MailNickName = $Name -replace "\W",'' }
    $settings = @{  'displayName'          = $Name
                    'mailNickname'         = $MailNickName
                    'mailEnabled'          = -not $AsSecurity
                    'securityEnabled'      = $AsSecurity -as [bool]
                    'visibility'           = $Visibility.ToLower()
                    'groupTypes'           = @()
    }
    if (-not $AsSecurity ) {
          $settings.groupTypes            += "Unified"
          if ($MyInvocation.InvocationName -eq 'New-GraphTeam' -and -not $PSBoundParameters.ContainsKey('AsTeam')) {
              $AsTeam = $true
          }
    }
    elseif ($AsAssignableToRole) {
          $settings['isAssignableToRole']  = $true
          $settings['visibility']          ='Private'
    }
    if ($Description) {
          $settings['description']         = $Description
    }
    #if we got owners or users with no ID, fix them at the end, if they have an ID add them now
    if ($Members) {
        $settings['members@odata.bind']    = @();
        foreach ($m in $Members) {
            if  ($m.id) {$settings['members@odata.bind'] += "$GraphUri/users/$($m.id)"}
            else        {$settings['members@odata.bind'] += "$GraphUri/users/$m"}
        }
    }
    #If we make someone else the owner of the group, we can't make it a team,
    #so parameter sets should ensure we can't get owners here if we are making a team.
    if ($Owners) {
        $settings['owners@odata.bind']     = @()
        foreach    ($o in $Owners)  {
            if     ($o.id) {$settings['owners@odata.bind']  += "$GraphUri/users/$($o.id)"}
            else{           $settings['owners@odata.bind']  += "$GraphUri/users/$o"}
        }
    }
    $webparams = @{
        Method     = 'Post'
        Uri        = "$GraphUri/groups"
        Body       = (ConvertTo-Json $settings)
        ContentType = 'application/json'
    }
    Write-Debug $webparams.body
    if ($Force -or $PSCmdlet.shouldprocess($Name,"Add new Group")) {
        Write-Progress -Activity 'Creating Group/Team' -CurrentOperation "Adding Group $Name"
        $group = Invoke-GraphRequest @webparams -As ([MicrosoftGraphGroup]) -Exclude "@odata.context","creationOptions"

        if (-not $AsTeam) {
            Write-Progress -Activity 'Creating Group/Team' -Completed
            return $group
        }
        elseif ($Group.GroupTypes) {
            Write-Progress -Activity 'Creating Group/Team' -CurrentOperation "Team-enabling Group $Name"
            $webparams.Uri   +=  "/$($group.id)/team"
            $webparams.Method = 'Put'
            $webparams.Body   = '{ }'
            $TimeToStop = [datetime]::Now.AddMinutes(2)
            $retries = 0
            do {
                try {
                    $team      = Invoke-GraphRequest @webparams -Exclude '@odata.context' -As ([MicrosoftGraphTeam]) |
                                    Add-Member -PassThru -NotePropertyName Mail -NotePropertyValue $group.Mail
                }
                catch {
                    $retries ++
                    Write-Progress -Activity 'Creating Group/Team' -CurrentOperation "Team-enabling Group $Name" -status "Retries $retries"
                    Start-Sleep -Seconds 5
                }
            }
            until ($team -or [datetime]::now -gt $TimeToStop)
            if (-not $team ) {
                Write-Warning "Group was created, but could not elevate it to a team."
                return $group
            }
            $team.Description = $group.description
            $team.Members     = $group.members
            $team.visibility  = $group.visibility

            if ($Owners) { $
                Write-Progress -Activity 'Creating Group/Team' -CurrentOperation "Setting Group ownership on $Name"
                Owners | Add-GraphGroupMember -Group $group -AsOwner -Force
            }
            Write-Progress -Activity 'Creating Group/Team' -Completed
            $team
        }
    }
}

function Set-GraphGroup             {
    <#
      .Synopsis
        Sets options on a group
      .Description
        Allows or blocks external senders, changes visibility or description and enables the group as a team.
        Other options for a team are set via Set-GraphTeam.
        Requires consent to use the Group.ReadWrite.All scope.
      .Example
       Get-GraphGroupList -Name consult | Set-GraphGroup -Description "People who do consulting work" -Force
       Finds the group(s) with a name which matches Consult* and sets the description without a confirmation prompt.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true,ConfirmImpact='High')]
    param   (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true,Position=0)]
        [ArgumentCompleter([GroupCompleter])]
        $Group ,
        #If specified, updates the group's displayName
        $DisplayName,
        #If specified, the group can receive external email; the option can be disabled with -AllowExternalSenders:$false.
        [switch]$AllowExternalSenders,
        #A new description for the group
        [string]$Description,
        #Enables team functionality on a group which does not yet have it enabled
        [switch]$EnableTeam,
        #If specified the group will be updated without prompting for confirmation.
        [switch]$Force
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        #ensure we have an ID for the group(s) we were passed. If we got a GUID in a string, we'll confirm it's a group and get the display name.
        $Group = foreach ($g in $Group) {
                  if     ($g.ID) {$g}
                  elseif ($g -is [String]) {Get-GraphGroup $g -ErrorAction Stop  }
                  else   {throw -Message 'Could not process Group parameter.'; return }
        }
        foreach ($g in $Group)  {
            $settings = @{}  #theme, preferredLanguage, preferredDataLocation, hideFromOutlookClients , hideFromAddressLists , classification, displayname
            if ($Description)       {$settings['description']           = $Description}
            if ($DisplayName)       {$settings['displayName']           = $DisplayName}
            if ($PSBoundparameters.ContainsKey('AllowExternalSenders')) {
                                     $settings['allowExternalSenders']  = [bool]$AllowExternalSenders
            }
            $webparams = @{
                 uri         = "$GraphUri/groups/$($g.ID)"
                 Method      = 'Patch '
                 Body        = (ConvertTo-Json $settings)
                 ContentType = 'application/json'
            }
            Write-Debug $webparams.Body
            if (($settings.Count -or $EnableTeam) -and
                ($Force -or $PSCmdlet.Shouldprocess($g.displayname,'Update Group'))) {
                if ($settings.Count) {
                    Invoke-GraphRequest @webparams | Out-Null
                }
                if ($EnableTeam ) {
                    $response  = Invoke-GraphRequest -Uri $webparams.uri
                    if ($response.resourceProvisioningOptions -contains 'Team')     {
                        Write-Warning  "Group $($g.displayName) is already team-enabled."
                    }
                    else {
                        $webparams.uri    += '/team'
                        $webparams.Method  = 'Put'
                        $webparams.Body    = "{ }"
                        Invoke-GraphRequest  @webparams | Out-Null
                    }
                }
            }
        }
    }
}

function Set-GraphTeam              {
    <#
      .Synopsis
        Updates the settings for a team
      .Description
        Requires consent to use the Group.ReadWrite.All scope
      .Example
        >Get-GraphTeam -byname accounts | Set-GraphTeam -AllowGiphy:$false
        Gets a the team(s) with a name that begins with accounts, and turns off Giphy content
        Note the use of -SwitchName:$false.
    #>

    [Cmdletbinding(SupportsShouldProcess=$true)]
    param   (
        #The team to update either as an ID or a team object with and ID.
        [ArgumentCompleter([GroupCompleter])]
        [Parameter(ValueFromPipeline=$true,Position=0)]
        $Team ,
        #Allow members to add or remove apps
        [switch]$AllowMemberAddRemoveApps,
        #Allow members to create update or remove connectors
        [switch]$AllowMemberCreateUpdateRemoveConnectors,
        #Allow members to create update or remove Tabs
        [switch]$AllowMemberCreateUpdateRemoveTabs,
        #Allow members to create or update Channels
        [switch]$AllowMemberCreateUpdateChannels,
        #Allow members to delete Channels
        [switch]$AllowMemberDeleteChannels,
        #Allow guests to create or update Channels
        [switch]$AllowGuestCreateUpdateChannels,
        #Allow guests to delete Channels
        [switch]$AllowGuestDeleteChannels,
        #Allow members to edit their own messages
        [switch]$AllowUserEditMessages,
        #Allow members to delete their own messages
        [switch]$AllowUserDeleteMessages,
        #Allow owners to delete mssages
        [switch]$AllowOwnerDeleteMessages,
        #Allow mentions of teams in messages
        [switch]$AllowTeamMentions,
        #Allow mentions of channels in messages
        [switch]$AllowChannelMentions,
        #Allow giphy graphics
        [switch]$AllowGiphy,
        #Rating for giphy graphics; either moderate or strict
        [ValidateSet('moderate', 'strict')]
        [string]$GiphyContentRating,
        #Allow stickers and memes
        [switch]$AllowStickersAndMemes,
        #Allow Custom memes
        [switch]$AllowCustomMemes
    )

    $webparams = @{Method      =  'PATCH'
                  ContentType  =  'application/json'}

    Write-Progress -Activity "Updating Team" -Status "Checking team is valid"
    if     ($Team.id)           {
        $group =  Invoke-GraphRequest -method get "$GraphUri/groups/$($Team.id)" -Headers $DefaultHeader
    }
    elseif ($Team -is [string] -and $team -match $GuidRegex ) {
        $group =  Invoke-GraphRequest -method get "$GraphUri/groups/$Team" -Headers $DefaultHeader
    }
    elseif ($Team -is [string]  ) {
        $group =  Get-GraphGroupList -Name $Team
    }
    if ($group.id -and $group.displayName -and $group.resourceProvisioningOptions -contains 'Team') {
        $webparams['Uri'] = "$GraphUri/teams/$($group.id)"
    }
    else   {
        Write-Progress -Activity "Updating Team" -Completed
        Write-Warning -Message 'Could not resolve the team';
        return
    }
    $settings          = @{}
    $memberSettings    = @{}
    $guestSettings     = @{}
    $messagingSettings = @{}
    $funSettings       = @{}

    if ($PSBoundparameters.ContainsKey('AllowMemberAddRemoveApps'))                {$memberSettings.allowAddRemoveApps                = [Bool]$AllowMemberAddRemoveApps}
    if ($PSBoundparameters.ContainsKey('AllowMemberCreateUpdateChannels'))         {$memberSettings.allowCreateUpdateChannels         = [Bool]$AllowMemberCreateUpdateChannels}
    if ($PSBoundparameters.ContainsKey('AllowMemberCreateUpdateRemoveConnectors')) {$memberSettings.allowCreateUpdateRemoveConnectors = [Bool]$AllowMemberCreateUpdateRemoveConnectors}
    if ($PSBoundparameters.ContainsKey('AllowMemberCreateUpdateRemoveTabs'))       {$memberSettings.allowCreateUpdateRemoveTabs       = [Bool]$AllowMemberCreateUpdateRemoveTabs}
    if ($PSBoundparameters.ContainsKey('AllowMemberDeleteChannels'))               {$memberSettings.allowDeleteChannels               = [Bool]$AllowMemberDeleteChannels}
    if ($PSBoundparameters.ContainsKey('AllowGuestCreateUpdateChannels'))          {$guestSettings.allowCreateUpdateChannels          = [Bool]$AllowGuestCreateUpdateChannels}
    if ($PSBoundparameters.ContainsKey('AllowGuestDeleteChannels'))                {$guestSettings.allowDeleteChannels                = [Bool]$AllowGuestDeleteChannels}
    if ($PSBoundparameters.ContainsKey('AllowUserEditMessages'))                   {$messagingSettings.allowUserEditMessages          = [Bool]$AllowUserEditMessages}
    if ($PSBoundparameters.ContainsKey('AllowUserDeleteMessages'))                 {$messagingSettings.allowUserDeleteMessages        = [Bool]$AllowUserDeleteMessages}
    if ($PSBoundparameters.ContainsKey('AllowOwnerDeleteMessages'))                {$messagingSettings.allowOwnerDeleteMessages       = [Bool]$AllowOwnerDeleteMessages}
    if ($PSBoundparameters.ContainsKey('AllowTeamMentions'))                       {$messagingSettings.allowTeamMentions              = [Bool]$AllowTeamMentions}
    if ($PSBoundparameters.ContainsKey('AllowChannelMentions'))                    {$messagingSettings.allowChannelMentions           = [Bool]$AllowChannelMentions}
    if ($PSBoundparameters.ContainsKey('AllowGiphy'))                              {$funSettings.allowGiphy                           = [Bool]$AllowGiphy}
    if ($PSBoundparameters.ContainsKey('AllowStickersAndMemes'))                   {$funSettings.allowStickersAndMemes                = [Bool]$AllowStickersAndMemes}
    if ($PSBoundparameters.ContainsKey('AllowCustomMemes'))                        {$funSettings.allowCustomMemes                     = [Bool]$AllowCustomMemes}
    if ($PSBoundparameters.ContainsKey('GiphyContentRating'))                      {$funSettings.giphyContentRating                   = $GiphyContentRating}  #the only string

    if ($memberSettings.Count)    {$settings['memberSettings']    = $memberSettings}
    if ($guestSettings.Count )    {$settings['guestSettings']     = $guestSettings}
    if ($messagingSettings.Count) {$settings['messagingSettings'] = $messagingSettings}
    if ($funSettings.Count)       {$settings['funSettings']       = $funSettings}

    if ($settings.Count) {
        $json = ConvertTo-Json $settings -Depth 10
        Write-Debug $json
        if ($PSCmdlet.ShouldProcess($group.displayName,'Update Team settings')) {
            Write-Progress -Activity "Updating Team" -CurrentOperation $group.displayName -Status "Committing changes"
            Invoke-GraphRequest @webparams -Body $json
            Write-Progress -Activity "Updating Team" -Completed
        }
    }
    else {Write-Warning -Message "Nothing to set"}
}

function Remove-GraphGroup          {
    <#
      .Synopsis
        Removes a group/team
      .Description
        Requires consent to use the Group.ReadWrite.All scope.
        The group may remain visible for a short time.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true,ConfirmImpact='High')]
    [Alias("Remove-GraphTeam")]
    param   (
        #The ID of the Group / team
        [Parameter(Mandatory=$true, Position=0,ValueFromPipeline=$true )]
        [ArgumentCompleter([GroupCompleter])]
        [Alias("Team")]
        $Group,
        #If specified the group will be removed without prompting
        [switch]$Force
    )
    process {
        $Group = foreach ($g in $Group) {
                if     ($g.ID) {$g}
                elseif ($g -is [String]) {Get-GraphGroup $g -ErrorAction Stop  }
                else   {throw 'Could not process Group parameter.'; return }
        }
        foreach ($g in $Group){
            if ($Force -or $PSCmdlet.Shouldprocess("'$($g.displayname)'","Delete Group")) {
                Invoke-GraphRequest -Method Delete  -Uri "$GraphUri/groups/$($g.id)/"
                Write-Verbose "REMOVED GROUP $($g.displayname)"
            }
        }
    }
}

function Add-GraphGroupMember       {
    <#
      .Synopsis
        Adds a user (or group) to a group/team as either a member or owner.
      .Description
        Because the group may be a team the this command has alias of Add-GraphTeamMember.
        it requires consent to use the Group.ReadWrite.All, Directory.ReadWrite.All, or
        Directory.AccessAsUser.All scope.
      .Example
        >$newGroup = New-GraphGroup -Name Test101
        >Get-GraphUserList -Filter "Department eq 'Accounts'" | Add-GraphGroupMember -Group $newGroup
        Creates a new group; then gets a list of users and adds them to the group.
      .Example
        >Add-GraphTeamMember -Team $Newteam -Member alex@contoso.com -AsOwner
        Adds an owner to a team, using aliases for both the command and the group parameter
    #>

    [Cmdletbinding(SupportsShouldprocess=$true)]
    [Alias("Add-GraphTeamMember")]
    param   (
        #The group / team either as an ID or a group/team object with an IDn
        [Parameter(Mandatory=$true, Position=0)]
        [ArgumentCompleter([GroupCompleter])]
        [Alias("Team")]
        $Group,
        #The user or nested-group to add, either as a UPN or ID or as a object with an ID
        [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
        [ArgumentCompleter([UPNCompleter])]
        $Member,
        #If specified the user will be added as an owner, otherwise they will be a standard member
        [switch]$AsOwner,
        #If specified group member will be added without prompting
        [Switch]$Force
    )
    begin   {
        #ensure we have an ID for the group(s) we were passed. If we got a GUID in a string, we'll confirm it's a group and get the display name.
        if (ContextHas -WorkOrSchoolAccount){
            $Group = foreach ($g in $Group) {
                if     ($g.ID) {$g}
                elseif ($g -is [String]) {Get-GraphGroup $g -select id,displayName -ErrorAction Stop  }
                else   {throw -Message 'Could not process Group parameter.'; return }
            }
        }
    }
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot

        foreach ($g in $Group) {
            #group(s) resolved in begin block so should have an ID and display name.
            if ($AsOwner) {$uri   = "$GraphUri/groups/$($g.ID)/owners/`$ref" }
            else          {$uri   = "$GraphUri/groups/$($g.ID)/members/`$ref"}
            #I'm not really expecting an array of users so I have left this is one call for each user.
            #To optimize it piped users could be collected in the process block and the work done in the end block
            foreach ($m in $member) {
                #if we weren't passed as a user as a an object, resolve what we did get ...
                if   (-not $m.id)  {
                    try   {$m     = Get-GraphUser -User $m -Select displayname}
                    catch {throw "Could not get a user matching $m"; return }
                    if (-not $m) {throw "Could not get a member ID"; return }
                }
                $body = ConvertTo-Json @{'@odata.id' = "$GraphUri/directoryObjects/$($m.id)"   }
                Write-Debug $body
                if ($Force -or $PSCmdlet.shouldprocess($m.displayname,"Add to Group '$($g.displayname)'")) {
                    Invoke-GraphRequest -Method post -Uri $uri -Body $body -ContentType 'application/json'
                    Write-Verbose "ADDED $($m.displayname) to group $($g.displayname)"
                }
            }
        }
    }
}

function Remove-GraphGroupMember    {
    <#
      .Synopsis
        Removes a user (or group) from a group/team
      .Description
        Because the group may be a team the command has an alias of Remove-GraphTeamMember.
        It requires consent to use the Group.ReadWrite.All, Directory.ReadWrite.All, or
        Directory.AccessAsUser.All scope.
      .Example
        Remove-GraphGroupMember -Group $g -FromOwners -Member alex@contoso.com -Force
        Removes a user from the owners of a group without prompting for confirmation.
      .Example
        Get-GraphUserList -Filter "Department eq 'Accounts'" | Remove-GraphGroupMember -Group $g
        Gets a list of users and removes them from from a group.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true,ConfirmImpact='High')]
    [Alias("Remove-GraphTeamMember")]
    param   (
        #The ID of the Group / team
        [Parameter(Mandatory=$true, Position=0)]
        [Alias("Team")]
        $Group,
        #A group object with an ID field, or a user object, user ID or UPN
        [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
        [ArgumentCompleter([UPNCompleter])]
        $Member,
        #If specified the member will be removed from the owners rather than members
        [switch]$FromOwners,
        #If specified the member will be removed without prompting for confirmation
        [switch]$Force
    )
    begin   {
        #ensure we have an ID for the group(s) we were passed. If we got a GUID in a string, we'll confirm it's a group and get the display name.
        $Group = foreach ($g in $Group) {
            if     ($g.ID) {$g}
            elseif ($g -is [String]) {Get-GraphGroup $g -select id,displayName -ErrorAction Stop  }
            else   {throw  'Could not process Group parameter.'; return }
        }
    }
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        foreach ($g in $Group) {
            #I'm not really expecting an array of users so I have left this is one call fo.r each user.
            #To optimize it piped users could be collected in the process block and the work done in the end block
            foreach ($m in $member) {
                if   (-not $m.id)  {
                    try   {$m = Get-GraphUser -User $m -Select ID,displayName}
                    catch {throw "Could not get a user matching $m"; return }
                    if (-not $m) {throw "Could not get a member ID"; return }
                }
                #group(s) resolved in begin block so should have an ID and display name.

                if ($FromOwners) { $uri = "$GraphUri/groups/$($g.ID)/owners/$($m.id)/`$ref" }
                else {             $Uri = "$GraphUri/groups/$($g.ID)/members/$($m.id)/`$ref"}
                if ($Force -or $PSCmdlet.Shouldprocess($m.displayName,"Remove from Group $($g.displayname)")) {
                    try {
                        Invoke-GraphRequest -Method Delete -Uri $uri
                        Write-Verbose "REMOVED $($m.displayname) from group $($g.displayname)"
                    }
                    catch {
                        If (($_.exception.response.statuscode.value__ -eq 404)) {
                            Write-Warning "Member '$($m.displayName)' was not found in the group $($g.displayname)"
                        }
                        else {$_}
                    }
                }
            }
        }
    }
}

function Export-GraphGroupMember    {
<#
    .synopsis
        Exports a list of group memberships to a CSV file
    .description
        Takes a list of groups (as a parameter or from the pipeline) and creates four columns
        * Action is either Add or Remove - on export it will always be add
        * MemberOf the name of ONE group the user should be added to or removed from
        * UserPrincipalName the name which will be used for add/remove operations.
        * Displayname just to make things easier to read, especially if UPNs are opaque
        If a file is specified it will be treated as CSV file for export,
        otherwise the objects are output
#>

    param   (
        [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)]
        #One or more group(s) to export
        [ArgumentCompleter([GroupCompleter])]
        $Group,
        #Destination for CSV output
        $Path,
        #If specified , output will be in Group name order (default is User name.)
        [switch]$OrderByGroup
    )
    begin   {
    $list = @()
    }
    process {
        foreach ($g in $group) {
            if ($g.DisplayName) {$groupName = $g.DisplayName}
            else                {$groupname = $g}
            $list += Get-GraphGroup $g -Members |
                    Select-Object -Property @{n='Action';  e={'Add'}} ,
                                            @{n='MemberOf';e={$groupName}},
                                            UserPrincipalName,
                                            Displayname
        }
    }
    end     {
        if ($OrderByGroup) {$list = $list | Sort-Object -Property Memberof, UserPrincipalName }
        else               {$list = $list | Sort-Object -Property UserPrincipalName, Memberof }
        if (-not $path) {return $list}
        else   {$list | Export-Csv -Path $Path -NoTypeInformation }
    }
}

function Import-GraphGroupMember    {
<#
    .synopsis
       Imports a list of group memberships from a CSV file
    .description
        Takes a list of CSV files and looks for three columns
        * Action is either Add or Remove - other values will cause the row to be ignored
        * MemberOf the name of ONE group the user should be added to or removed from
        * UserPrincipalName the name which will be used for add/remove operations.
        for each named group the command fetches the membership, users in the group,
        who are marked "remove" in the file will be removed, and users
        marked "add" in the file who are not in the group will be added.
#>

    [cmdletbinding(SupportsShouldProcess=$true,ConfirmImpact='high')]
    param   (
        #One or more files to read for input.
        [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)]
        $Path,
        #Usually the command will prompt for confirmation -Force disables this primpt
        [switch]$Force,
        #Supresses output of Added, Removed, or No action messages for each row in the file.
        [switch]$Quiet
    )
    begin   {
        $list = @()
    }
    process {
        foreach ($p in $path) {
            if (Test-Path $p) {$list += Import-Csv -Path $p}
            else { Write-Warning -Message "Cannot find $p" }
        }
    }
    end     {
        if (-not $Quiet) { $InformationPreference = 'continue'  }
        $groups = ($List | Group-Object -NoElement -Property memberof).Name
        foreach ($g in $groups) {
            $w = $Null
            $Members = (Get-GraphGroup $g -Members -WarningAction SilentlyContinue -WarningVariable W).UserPrincipalName
            if ($w) {Write-Warning "Skipping Group $g it did not match a group." ; continue}
            foreach    ($member in $list.where({$_.memberof -eq $g}) ) {
                $upn =  $member.UserPrincipalName
                if    (($member.Action -eq 'Add' -and $upn -notin $Members) -and
                       ($force -or $PSCmdlet.ShouldProcess($upn,"Add user to group'$g'"))) {
                        Add-GraphGroupMember -Force -Group $g -Member $upn
                        Write-Information "Added $UPN user to group'$g'"
                }
                elseif (($member.Action -eq 'Remove' -and $upn -in $Members) -and
                        ($force -or $PSCmdlet.ShouldProcess($upn,"Remove member from group'$g'"))){
                        Remove-GraphGroupMember -Force -Group $g -Member $upn
                        Write-Information "Removed $UPN user from group'$g'"
                }
                else   {Write-Information -Message "No action needed for $g / $upn"}
            }
        }
    }
}

function Import-GraphGroup          {
<#
    .synopsis
       Imports a list of groups from a CSV file
    .description
        Takes a list of CSV files and looks for four columns
        * Action is either Add or Remove - other values will cause the row to be ignored
        * DisplayName the name which will be used for add/remove operations.
        * Description - the longer text describing the group
        * Type is either Security to configure a non-mail-enabled Security group,
          or Team, to teams enable a group. Blank or other values will create a non-security
          email enabled group which can be teams-enabled later.
        * Visibility - one of 'private', 'public', 'hiddenmembership'
        The command fetches the list of existing groups, any marked "remove" in the file
        will be removed, and marked "add" who are not in the group will be added using
        the type, visibility, and description settings.
        IF the group exists no check is done to see that it matches the file settings.
#>

    [cmdletbinding(SupportsShouldProcess=$true)]
    param   (
        #One or more files to read for input.
        [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)]
        $Path,
        #Disables any prompt for confirmation
        [switch]$Force,
        #Supresses output of Added, Removed, or No action messages for each row in the file.
        [switch]$Quiet
    )
    begin   {
        $list = @()
    }
    process {
        foreach ($p in $path) {
            if (Test-Path $p) {$list += Import-Csv -Path $p}
            else { Write-Warning -Message "Cannot find $p" }
        }
    }
    end     {
        if (-not $Quiet) { $InformationPreference = 'continue'  }
        $existingGroups = Get-GraphGroupList
        $existingNames  = $existingGroups.DisplayName
        foreach ($group in $list) {
            $displayName = $group.DisplayName
            if (($Group.Action -eq 'Remove' -and $displayname -in $existingNames) -and
                ($force -or $PSCmdlet.ShouldProcess($displayname,"Remove group "))){
                        Remove-GraphGroup -Force -Group $displayname
                        Write-Information "Removed group'$displayname'"
            }
            elseif (($Group.Action -eq 'Add' -and $displayname -notin $existingNames) -and
                ($force -or $PSCmdlet.ShouldProcess($displayname,"Add new group"))){
                    $params = @{Force=$true; Name=$displayName}
                    if ($group.Type -match 'Security') {$params['AsSecurity'] = $true}
                    if ($group.Type -match 'Team')     {$params['AsTeam'] = $true}
                    if ($group.Visibility)             {$params['Visibility'] = $group.Visibility}
                    if ($group.Description)            {$params['Description'] = $group.Description}
                    New-GraphGroup @params
                    Write-Information "Added group'$displayName'"
            }
            else {  Write-Information "No action taken for group '$displayName'"}
        }
    }
}

function New-GraphTeamPlan          {
    <#
      .Synopsis
        Creates new a plan (in the planner app) for a team.
    #>

    [cmdletbinding(SupportsShouldProcess=$true)]
    [outputType([Microsoft.Graph.PowerShell.Models.MicrosoftGraphPlannerPlan])]
    param   (
        #The ID of the team
        [parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)]
        [Alias("Group")]
        [ArgumentCompleter([GroupCompleter])]
        $Team,
        #Name(s) of the plan(s) to add to this team.
        [parameter(Mandatory=$true, Position=1)]
        $PlanName,
        #If Specified the plan will be added without confirmation
        [Switch]$Force
    )
    begin   {
    }
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        if     ($Team.id)                   {$settings =  @{owner = $team.id} }
        elseif ($Team -is [string] -and
                $Team -match $GUIDRegex )   {$settings =  @{owner = $team} }
        elseif ($Team -is [string]) {
                $Team = Get-GraphTeam $Team; $settings =  @{owner = $team.id}
        }

        foreach ($p in $PlanName) {
            $settings["title"] = $p
            $webParams = @{Method      = 'Post'
                           URI         = "$GraphUri/planner/plans"
                           Contenttype = 'application/json'
                           Body        = (ConvertTo-Json $settings)
            }
            Write-Debug $webParams.Body
            if ($Force -or  $PSCmdlet.ShouldProcess($P,"Add Team Planner")) {
                $result    = Invoke-GraphRequest @webParams -ErrorAction Stop
                $etag      =  $result.'@odata.etag'
                $odatakeys =  $result.Keys.Where({$_ -match "@odata\."})
                foreach ($k in $odatakeys) {$result.Remove($k)}
                $planobj = New-Object  -Property $result -TypeName MicrosoftGraphPlannerPlan |
                    Add-Member -PassThru -NotePropertyName  etag -NotePropertyValue $etag |
                    Add-Member -PassThru -NotePropertyName  Team -NotePropertyValue $Team
                if ($planObj.owner) {
                    $owner = (Invoke-GraphRequest  -Uri "$GraphUri/directoryobjects/$($planObj.owner)").displayname
                    Add-Member -InputObject $planObj -NotePropertyName OwnerName -NotePropertyValue $owner
                }
                if ($planObj.createdBy.user.id -and $planObj.createdBy.user.id  -eq $planObj.owner) {
                    Add-Member -InputObject $planObj -MemberType NoteProperty -Name CreatorName -Value $owner
                }
                elseif ($planObj.createdBy.user.id) {
                    $creator = (Invoke-GraphRequest  -Uri "$GraphUri/directoryobjects/$($planObj.createdBy.user.id)").displayname
                    Add-Member -InputObject $planObj -MemberType NoteProperty -Name CreatorName -Value $creator
                }
                $planObj
            }
        }
    }
}

function Get-GraphGroupConversation {
    <#
      .Synopsis
        Gets details of group converstation from outlook, or its threads.
      .Description
        Requires consent to use the Group.Read.All scope
      .Example
        Get-GraphGroupList -Name consult | Get-GraphGroup -Conversations | Get-GraphGroupConversation -Threads
        Gets group(s) matching the name "consult*" , finds their conversations and for each one gets the threads in the conversation
        Note, unless you are dealing with conversations which have multiple threads, it is easier to do Get-GraphGroup -Threads
    #>

    [Cmdletbinding()]
    [Alias("Get-GraphTeamConversation","Get-GraphConversation")]  #Strictly Conversations belong to a group in Outlook, not a Team in Microsoft teams, but let either name be used.
    param   (
        #The Conversation, either as an ID or an object.
        [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1, ParameterSetName='OneConversation')]
        $Conversation,
        #The group where the conversation is found,it is not part of can't be found from the conversation object
        [Parameter(ParameterSetName='InTeam',Position=0)]
        [Parameter(ParameterSetName='OneConversation',Position=0)]
        [ArgumentCompleter([GroupCompleter])]
        [Alias("Team")]
        $Group,
        #When selecting the Conversations for a group narrows the list by the name of the topic
        [Parameter(ParameterSetName='InTeam', Position=3)]
        $Topic = "*",
        #If specified selects the conversation's threads, otherwise an object representing the conversation itself is returned.
        [Switch]$Threads
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        if ( -not $Conversation) {
            $conversations = Get-GraphGroup -Group $Group -Conversations | Where-Object -Property Topic -like $Topic
            if ($Threads) {$conversations | Get-GraphGroupConversation -Threads}
            else          {$conversations}
            return
        }
        if     ($Conversation.Group)       {$groupID = $Conversation.Group}
        elseif ($Group.ID)                 {$groupID = $Group.ID}
        elseif ($Group -is [String]  -and
                $Group -match $GUIDRegex)  {$groupID = $Group}
        elseif ($Group -is [String])       {$groupID = (Get-GraphGroup -Group $group -NoTeamInfo ).id}
        if     ($groupID -notmatch $GUIDRegex) {
                Write-Warning -Message 'Could not resolve group ID'; return
        }
        if     ($Conversation.id)          {$Conversation = $Conversation.id}
        if ($Threads) {
            $uri    = "$GraphUri/groups/$groupID/conversations/$conversation/Threads"
            Invoke-GraphRequest  -Uri $uri -ValueOnly -AsType ([MicrosoftGraphConversationThread]) |
                Add-Member -PassThru -NotePropertyName Group        -NotePropertyValue $GroupID   |
                Add-Member -PassThru -NotePropertyName Conversation -NotePropertyValue $Conversation
        }
        else     {
            Invoke-GraphRequest  -Uri ("$GraphUri/groups/$groupID/conversations/$conversation"  +'?$expand=Threads') -AsType ([MicrosoftGraphConversation]) -ExcludeProperty '@odata.context' |
                 Add-Member -PassThru -NotePropertyName Group -NotePropertyValue $GroupID
        }
    }
}

function Get-GraphGroupThread       {
    <#
      .Synopsis
        Gets a thread in a Group conversation in outlook, or its posts
      .Description
        Requires consent to use the Group.Read.All scope
      .Example
        >Get-GraphUser -Teams | Get-GraphGroup -Threads | Get-GraphGroupThread -Posts |
             ft -a -Wrap @{n="from";e={$_.from.emailaddress.name}},CreatedDateTime,Topic,@{n="Body";e={$_.body.content}}
        Gets a users teams, for each one gets their threads, and for each thread gets the outlook posts
        Displays the result as a table showing from, message date, thread topic and message body
        Note this uses Get-GraphGroup as an alias for Get-GraphTeams
    #>

    [Cmdletbinding()]
    [Alias("Get-GraphTeamThread")]
    param   (
        #The group thread, either as an ID or as a thread object (which may have the team/group as property)
        [Parameter(ParameterSetName='SingleThread', Position=1, ValueFromPipeline=$true, Mandatory=$true)]
        $Thread,
        #The group holding the thread (s), if thread is either not passed or is just the ID of a thread.
        [Alias("Team")]
        [Parameter(ParameterSetName='GroupThreads', Position=0)]
        [Parameter(ParameterSetName='SingleThread', Position=0)]
        [ArgumentCompleter([GroupCompleter])]
        $Group,
        #When selecting the threads for a group narrows the list by the name of the topic
        [Parameter(ParameterSetName='GroupThreads')]
        $Topic = '*',
        #If specified, returns the posts in the thread
        [Switch]$Posts
    )
    begin   {

        $webparams = @{Headers         = @{"Prefer" ='outlook.body-content-type="text"' }
                       AsType          =  ([MicrosoftGraphConversationThread])
                       ExcludeProperty = '@odata.context' }
    }
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        if  (-not $Thread) {
            $threads = Get-GraphGroup -Group $Group -Threads | Where-Object -Property Topic -like $topic
            if ($posts) {$threads | Get-GraphGroupThread -Posts}
            else        {$threads}
            return
        }
        if     ($Thread.Group)                 {$groupid  = $Thread.group}
        elseif ($Group.ID)                     {$groupID  = $Group.ID}
        elseif ($Group -is [String] -and
                $Group -match $GUIDRegex)      {$groupID  = $Group}
        elseif ($Group -is [String])           {$groupID  = (Get-GraphGroup -Group $group -NoTeamInfo ).id}

        if     ($groupID -notmatch $GUIDRegex) {Write-Warning -Message 'Could not resolve group ID'; return }

        if     ($Thread.id)                    {$threadID = $Thread.id}
        elseif ($Thread -is [string])          {$threadID = $Thread}
        else   {Write-Warning -Message 'Could not resolve thread ID'; return}

        $t = Invoke-GraphRequest @webparams -Uri "$GraphUri/groups/$Groupid/Threads/$threadID`?`$expand=Posts"  |
                Add-Member -PassThru -NotePropertyName Group -NotePropertyValue $Groupid
        foreach  ($post in $t.posts) {
            Add-Member -InputObject $post -MemberType NoteProperty -Name Group  -Value $groupid
            Add-Member -InputObject $post -MemberType NoteProperty -Name Thread -Value $t.ID
            Add-Member -InputObject $post -MemberType NoteProperty -Name Topic  -Value $t.Topic
        }
        if ($Posts) {$t.posts}
        else        {$t}
    }
}

function Add-GraphGroupThread       {
    <#
      .Synopsis
        Starts a new thread in a group in outlook.
      .Description
        Requires consent to use the Group.ReadWrite.All scope
      .Example
        >
        >$G = Get-GraphGroup consultants
        >Add-GraphGroupThread -Group $G -Subject "Running tests.." -Content "We will be running a full test pass this afternoon"
        Gets a group by name and creates a new thread with a message using a plain text body.
      .Example
        >$thread = Add-GraphGroupThread -passthru -Group $G -Subject "Ruuning tests.." -ContentType HTML -Content "<b><i>Drum-Roll...</i>A full test pass is running... Watch this space</i>"
        Uses the group from the previous example, and creates a thread with an HTML body, and keeps a reference to it.
      .link
        Send-GraphGroupReply
    #>

    [Cmdletbinding(SupportsShouldprocess=$true, ConfirmImpact='Low')]
    param   (
        #The group where the thread will be added
        [Parameter(Mandatory=$true,Position=0)]
        [Alias("Team")]
        [ArgumentCompleter([GroupCompleter])]
        $Group,
        #The subject line for the thread
        [Parameter(Mandatory=$true, Position=1)]
        [Alias("Subject")]
        $ThreadTopic,
        #The Message body - text by default, specify -contentType if using HTML
        [Parameter(Mandatory=$true, Position=2)]
        [String]$Content,
        #The content type, (Text by default) or HTML
        [ValidateSet("Text","HTML")]
        [String]$ContentType = "Text",
        #if Specified the message will be created without prompting; this is the default, unless $confirm preference has been changed
        [switch]$Force,
        #if Specified an object containing the Thread ID will be returned
        [switch]$PassThru
    )
    ContextHas -WorkOrSchoolAccount -BreakIfNot

    if     ($Group.ID)                {$groupID  = $Group.ID}
    elseif ($Group -is [String] -and
            $Group -match $GUIDRegex) {$groupID = $Group}
    elseif ($Group -is [String])      {$groupID =  (Get-GraphGroup -Group $group -NoTeamInfo ).id}

    if ($groupID -notmatch $GUIDRegex)  {Write-Warning -Message 'Could not process Group parameter.'; return }

    $Settings  = @{ 'topic'       = $ThreadTopic
                    'posts'       = @( @{body= @{'content'     = $Content
                                                 'contentType' = $ContentType}})
    }
    $webparams = @{ 'URI'         = "$GraphUri/groups/$groupID/threads/"
                    'Method'      = 'Post'
                    'ContentType' = 'application/json'
                    'Body'        = (ConvertTo-Json $settings -Depth 5)
    }
    Write-Debug $webparams.Body

    if ($force -or $PSCmdlet.Shouldprocess($ThreadTopic,"Create New thread")) {
        $t = Invoke-GraphRequest  @webparams
        if ($PassThru) {
            Start-Sleep -Seconds 2
            Get-GraphGroupThread -Group $Groupid -Thread $t.id
        }
    }
}

function Remove-GraphGroupThread    {
    <#
      .Synopsis
        Removes a thread from a group in outlook
      .Example
        Get-GraphGroup -ByName consultants -Threads | where topic -eq "Today's tests..." | Remove-GraphGroupThread
        Finds the threads for a named group; isolates one by topic name, and removes it.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true, ConfirmImpact='High')]
    param   (
        #The thread to remove, either as an ID or a thread object containing an ID, and possibly a conversation ID and group ID
        [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
        $Thread,
        #The conversation the thread is part of.
        $Conversation,
        #The group from which the thread is to be removed, either as an ID or a group object containing an ID
        [Alias("Team")]
        [ArgumentCompleter([GroupCompleter])]
        $Group,
        #if Specified the thread will be deleted without prompting.
        [switch]$Force
    )
    process {
        contexthas -WorkOrSchoolAccount -BreakIfNot
        if     ($Thread.group)             {$groupid  = $Thread.group}
        elseif ($Group.ID)                 {$groupID = $Group.ID}
        elseif ($Group -is [String]  -and
                $Group -match $GUIDRegex)  {$groupID = $Group}
        elseif ($Group -is [String])       {$groupID = (Get-GraphGroup -Group $group -NoTeamInfo ).id}
        if     ($groupID -notmatch $GUIDRegex) {
                Write-Warning -Message 'Could not resolve group ID'; return
        }
        if     ($Thread.Conversation)         {$conversationID = $thread.Conversation}
        elseif ($Conversation.id)             {$conversationID = $Conversation.id}
        elseif ($conversationID -is [string]) {$conversationID = $Conversation}
        if (-not $conversationID) {
                Write-Warning -Message 'Could not resolve Conversation ID'; return
        }

        if     ($Thread.ID)           {$threadid = $Thread.id  }
        elseif ($Thread -is [string]) {$threadid = $Thread.id  }
        else   {Write-Warning 'Could not resolve the Thread ID' ; return}

        $webparams = @{ 'uri'    =  "$GraphUri/groups/$GroupID/conversations/$conversationID/threads/$threadID" }
        Write-Progress -Activity "Deleting thread" -Status "Checking existing thread"
        try   {$thread  = Invoke-GraphRequest -Method Get @webparams }
        catch {
            if ($_.exception.response.statuscode.value__ -eq 404) {
                Write-warning 'Thread not found, it may have been deleted already'
                return
            }
            else {
                throw $_ ;
                return
            }
        }
        if (-not $thread) {throw "Could not get the thread to delete"; return}
     Write-Progress -Activity "Deleting thread" -Completed
        if ($Force -or $PSCmdlet.Shouldprocess($thread.topic,"Delete thread")) {
            Write-Progress -Activity "Deleting thread" -Status "Sending delete instruction"
            Invoke-GraphRequest -Method Delete  @webparams
            Write-Progress -Activity "Deleting thread" -Completed
        }
    }
}

function Send-GraphGroupReply       {
    <#
      .Synopsis
        Replies to a group's post in outlook.
      .Example
        >$thread.posts[0] | Send-GraphGroupReply -content '<b><font color="green">Success!!</font> Go team!</b>' -ContentType HTML
        One of the examples for Add-GraphGroupThread left the result of a creating a new thread in $thread
        This takes the only post in the new thread and creates a reply to it with the content in HTML format.
      .Example
        >
        >$post = Get-GraphGroup -ByName consultants -Threads | where topic -eq "Today's tests..." | Get-GraphGroupThread -Posts | select -last 1
        >Send-GraphGroupReply $post -Content "Please join a celebration of the successful test at 4PM"
        This example finds threads for the consultants group, Isolates the one with the topic of
        "Today's Tests..." and finds the last post in the thread. It then posts are reply with the content as plain text.
      .link
        Add-GraphGroupThread
    #>

    [Cmdletbinding(SupportsShouldprocess=$true, ConfirmImpact='Low')]
    param   (
        #The Post being replied to, either as an ID or a post object containing an ID which may identify the thread and group
        [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
        $Post,
        #The thread containing the post (if not embedded in the post itself), as an ID or object, which may identify the group
        $Thread,
        #The group containing the thread (if not embedded in the Post or thread) as an ID or object
        [Alias("Team")]
        [ArgumentCompleter([GroupCompleter])]
        $Group,
        #The Message body - text by default, specify -contentType if using HTML
        [Parameter(Mandatory=$true)]
        [String]$Content,
        #The type of content, text by default or HTML
        [ValidateSet("Text","HTML")]
        [String]$ContentType = "Text",
        #if Specified the message will be created without prompting.
        [switch]$Force
    )
    ContextHas -WorkOrSchoolAccount -BreakIfNot

    if     ($Post.Group)          {$groupID  = $Post.group}
    elseif ($Thread.Group)        {$groupID  = $Thread.group}
    elseif ($Group.ID)            {$groupID  = $Group.ID}
    elseif ($Group -is [string])  {$groupID  = $Group}
    else   {Write-warning -Message 'Could not resolve the group ID.' ; return}

    if     ($Post.Thread)         {$threadID = $Post.Thread}
    elseif ($Thread.ID)           {$threadID = $Thread.id  }
    elseif ($Thread -is [String]) {$threadID = $Thread.id  }
    else   {Write-warning -Message 'Could not resolve the Thread ID.' ; return}

    if     ($Post.ID)             {$PostID   = $Post.ID}
    elseif ($Post -is [String])   {$PostID = $Post  }
    else   {Write-warning -Message 'Could not resolve the Post ID.' ; return}

    if (-not ($PostID -and $threadID -and $groupID)) {throw "Could not find Group, Thread and Post IDs from supplied parameters."; Return}


    $uri       =  "$GraphUri/groups/$groupID/threads/$threadID/posts/$postid"
    Write-Progress -Activity 'Posting reply to thread' -Status 'Checking parent message'
    try   {   $p  = Invoke-GraphRequest -Method Get -uri $uri }
    catch {       throw "Could not get the post to reply to"; return}
    if (-not $p) {throw "Could not get the post to reply to"; return}

    $Settings  = @{ 'Post' = @{'body'= @{'content'=$Content; 'contentType'=$ContentType}}}
    $Json      = ConvertTo-Json $settings
    Write-Debug $Json

    if ($Force -or $PSCmdlet.Shouldprocess($thread.topic,"Reply to thread")) {
        $uri     += "/Reply"
        Write-Progress -Activity 'Posting reply to thread' -Status 'sending reply'
        Invoke-GraphRequest -Method Post -Uri $URI  -Body $Json -ContentType "application/json"
        Write-Progress -Activity 'Posting reply to thread' -Completed
    }
}

function Get-ChannelMessagesByURI   {
    <#
      .synopsis
        Helper function to add get and expand messages or replies to messages
    #>

    param   (
        [parameter(Position=0,ValueFromPipeline=$true)]
        $URI,
        $Top = 20
    )
    process {
        $msglist = @()
        Write-progress -Activity 'Getting messages' -Status "Reading Messages"
        $result   = (Invoke-GraphRequest -Uri $uri)
        $msgList  += $result.value
        while ($result.'@odata.nextLink' -and $result.'@odata.count' -gt 0 -and $msgList.Count -lt $top ) {
            Write-progress -Activity 'Getting messages' -Status "Reading $($ch.displayname) Messages" -CurrentOperation "$($msglist.count) so far"
            $result   = Invoke-GraphRequest -Uri $result.'@odata.nextLink'
            $msgList += $result.value
        }
        $msgList |
            ForEach-Object {New-Object -TypeName MicrosoftGraphChatMessage -Property $_ } |
                Sort-Object -Property createdDateTime -Descending| Select-Object -First $top
       <# $userHash = @{}
        Write-Progress -Activity 'Getting messages' -Status "Expanding User information"
        $msglist.from.user.id | Sort-Object -Unique | foreach-object {
            $userHash[$_] = ( Invoke-GraphRequest -Uri "$GraphUri/directoryObjects/$_").displayName
        }#>

        Write-progress -Activity 'Getting messages' -Completed
        <#foreach ($msg in $msgList) {
            if ($msg.from.user.id) {
                Add-Member -InputObject $msg -NotePropertyName FromUserName -NotePropertyValue $userHash[$msg.from.user.id]
            }
        }#>

    }
}

function Get-GraphChannel           {
    <#
      .Synopsis
        Gets details of a channel, or its Tabs or messages shown in Teams
      .Example
        >Get-GraphTeam -ByName consultants -ChannelName general | Get-GraphChannel -Tabs
        Gets channels for the team(s) with a name beginning 'Consultants' and selects channel(s)
        with a name beginning "general"; then gets the tabs shown in Teams for this channel
      .Example
        >Get-GraphTeam -ByName consultants -ChannelName general | Get-GraphChannel -Messages
        This follows the same method for getting the Teams but this time returns messaes in the channel
      .Example
        >Get-GraphChannel -Team $c -ByName general -Messages
        This is a variation on the previous example - here $c holds an object describing
        the consultants Team and the channel and its messages are retieved using a single command.
      .Example
        >Get-GraphChannel -Team $c -ByName -channel ""
        This previous example didn't explictly specify the channel parameter when using the
        ByName switch; this version does and specifies and empty string so it will return all
        channels (channel is a required parameter, but it can be an empty string)
    #>

    [Cmdletbinding(DefaultparameterSetName="None")]
    [Alias("Get-GraphTeamChannel")]
    param   (
        #The channel either as a name, an ID or as a channel object (which may contain the team as a property)
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, parameterSetName="CHMsgs")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, parameterSetName="CHTabs")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, parameterSetName="CHFolder")]
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, parameterSetName="CHFiles")]
        $Channel,
        #The ID of the team if it is not in the channel object. If not specified the current users teams are tried
        [Parameter(Position=0)]
        [ArgumentCompleter([TeamCompleter])]
        $Team,
        #If specified gets the channel's Tabs
        [Parameter(parameterSetName="NoCHTabs", Mandatory=$true)]
        [Parameter(parameterSetName="CHTabs", Mandatory=$true)]
        [switch]$Tabs,
        #If specified gets the channel's Tabs
        [Parameter(parameterSetName="NoCHFolder", Mandatory=$true)]
        [Parameter(parameterSetName="CHFolder", Mandatory=$true)]
        [switch]$Folder,
        [Parameter(parameterSetName="NoCHFiles", Mandatory=$true)]
        [Parameter(parameterSetName="CHFiles", Mandatory=$true)]
        [switch]$Files,
        #if Specified uses the beta api to get the channel's messages.
        [Parameter(parameterSetName="NoCHMsgs")]
        [Parameter(parameterSetName="CHMsgs")]
        [Alias("Msgs")]
        [switch]$Messages,
        #If specified, returns the top n messages, otherwise the command will attempt to get all messages. The server may return more than the specified number.
        [Parameter(parameterSetName="NoCHMsgs")]
        [Parameter(parameterSetName="CHMsgs")]
        $Top
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        #We want team to tab complete on an empty line, but than can mean if channel is the only thing on the command line it goes into $team
        if ($Team -is [MicrosoftGraphChannel]) {
            $Channel = $Team
            $Team    = $Null
        }
        if ($Channel -is [string] -and $Channel -notmatch '@thread') {
            $Channel = Get-GraphTeam -Team $Team -Channels -ChannelName $channel
        }
        elseif (-not $Channel) {
            $Channel = Get-GraphTeam -Team $Team -Channels
        }
        #ByName might return multiple channels. Support -channel being given an array of channels.
        foreach ($ch in $channel) {
            if     ($ch.Team)           {$teamID    = $ch.team }
            elseif ($Team.ID)           {$teamID    = $Team.ID }
            elseif ($Team -is [string]) {$teamID    = $Team    }
            else   {Write-Warning -Message 'Could not resolve the team for this channel'; return}
            if     ($ch.id  )           {$channelID = $ch.ID   }
            elseif ($ch -is [string])   {$channelID = $ch      }
            else   {Write-Warning -Message 'Could not resolve the channel ID'; return}
            if (-not ($teamid -and $channelID)) {Write-warning -Message "You need to provide a team ID and a Channel ID"; return}
            elseif   ($Messages -or $Top)              {
                $uri      =  "https://graph.microsoft.com/beta/teams/$teamID/channels/$channelID/messages"
                if ($top) {Get-ChannelMessagesByURI -URI $uri -Top $Top}
                else      {Get-ChannelMessagesByURI -URI $uri}
                return
            }
            elseif   ($Tabs)                           {
                if ($ch.DisplayName) {Write-Progress -Activity 'Getting Tab information' -CurrentOperation $ch.DisplayName}
                else                 {Write-Progress -Activity 'Getting Tab information' }
                $uri = "$GraphUri/teams/$teamID/channels/$channelID/tabs?`$expand=teamsApp"
                Invoke-GraphRequest -Uri $uri  -ValueOnly -astype ([MicrosoftGraphTeamsTab]) |
                    ForEach-Object { #newly created tabs have a teamsAppId property. Existing apps have to look at the teamsApp and its ID. Make them the same!
                        $_.TeamsAppID = $_.TeamsApp.ID
                        $_
                    }
                Write-Progress -Activity 'Getting Tab information' -Completed
            }
            elseif   ($Folder -or $Files)              {
                if ($ch.DisplayName) {Write-Progress -Activity 'Getting Folder information' -CurrentOperation $ch.DisplayName}
                else                 {Write-Progress -Activity 'Getting Folder information' }
                $uri = "$GraphUri/teams/$teamID/channels/$channelID//filesFolder"
                $f = Invoke-GraphRequest -Uri $uri -AsType  ([MicrosoftGraphDriveItem]) -ExcludeProperty '@odata.context'
                if ($folder) {$f}
                else         {
                    $uri = "$GraphUri/drives/$($f.ParentReference.DriveId)/items/$($f.id)/children"
                    Invoke-GraphRequest -Uri $uri -ValueOnly -ExcludePropert '@odata.etag', '@microsoft.graph.downloadUrl' -AsType ([MicrosoftGraphDriveItem])
                }
                Write-Progress -Activity 'Getting Folder information' -Completed
            }
            elseif   ($ch -is [MicrosoftGraphChannel]) {
                #Have already fetched the channel once so don't fetch it again
                $ch
            }
            else     {
                if ($ch.DisplayName) {Write-Progress -Activity 'Getting Channel information' -CurrentOperation $ch.DisplayName}
                else                 {Write-Progress -Activity 'Getting Channel information' }
                Invoke-GraphRequest -Uri  "$GraphUri/teams/$teamID/channels/$channelId" -ExcludeProperty '@odata.context' -AsType ([MicrosoftGraphChannel]) |
                    Add-Member -PassThru -NotePropertyName Team -NotePropertyValue $teamID
                Write-Progress -Activity 'Getting Channel information' -Completed
            }
        }
    }
}

function New-GraphChannel           {
    <#
      .Synopsis
        Adds a channel to a team
      .Description
        This requires the Group.ReadWrite.All scope.
      .Example
       >$newChannel = New-GraphChannel -Team $newTeam -Name $newProjectName -Description "For anything about project $newProjectName"
       $newTeam holds the result of creating a team with New-GraphTeam...
       $newProjectName holds the name of a project the team will be working on.
       This command creates a new channel in Teams, and stores the result in a variable
       which can then be used to post messages to the channel, or add tabs to it.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true)]
    [Alias("Add-GraphTeamChannel")]
    param   (
        #The team where the channel will be added, either as an ID or a team object
        [Parameter( Mandatory=$true, Position=0)]
        [ArgumentCompleter([TeamCompleter])]
        $Team,
        #Display name for the new channel
        [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
        [Alias("DisplayName")]
        [String[]]$Name,
        #Description for the new channel
        [String]$Description
    )
    begin   {
        $webparams = @{Method = "POST"
                       ContentType = "application/json"
        }
    }
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        if     ($Team.id) {$team = $team.id }
        elseif ($Team  -is [string] -and $Team -notmatch $GUIDRegex) {
                $Team = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
        }       #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams
        #intentionally fail if the previous step returns an array or nothing - and it won't return groups which aren't team enabled. We should now have a GUID
        if     ($Team  -is [string] -and $Team -match $GUIDRegex) {
                $webparams['uri'] = "$GraphUri/teams/$Team/channels"
        }
        else  { Write-Warning "Could not resolve $($PSBoundParameters['team']) to team-enabled group." ; return        }

        foreach ($n in $Name) {
            if (Get-GraphTeam  $team -ChannelName $n  ) {
                Write-Warning -Message "Channel '$n' already exists in team '$($PSBoundParameters['team'])'."
                continue
            }

            $Settings  = @{"displayName" = $n}
            if ($Description) {$settings["description"] = $Description}
            $webparams['body'] = ConvertTo-Json $settings
            Write-Debug $webparams['body']

            if ($PSCmdlet.Shouldprocess($n,"Create channel")) {
                Invoke-GraphRequest @webparams -ExcludeProperty '@odata.context' -AsType ([MicrosoftGraphChannel]) |
                        Add-Member -PassThru -NotePropertyName Team -NotePropertyValue $team
            }
        }
    }
}

function Remove-GraphChannel        {
    <#
      .Synopsis
        Removes a channel from a team
      .Description
        This requires the Group.ReadWrite.All scope.
      .Example
        >Get-GraphTeam -ByName Developers -ChannelName "Project Firebird" | Remove-GraphChannel
        Finds a channel by name from a named team , and removes it.
    #>

    [Cmdletbinding(SupportsShouldprocess=$true, ConfirmImpact='High')]
    param   (
        #The channel to delete; either as an ID, or a channel object
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $Channel,
        #A team object or the ID of the team, if it can't be derived from the channel.
        [ArgumentCompleter([TeamCompleter])]
        $Team,
        #if Specified the channel will be deleted without prompting
        [switch]$Force
    )
    process {

        if ($Channel.Team) { $Team    = $Channel.team }
        elseif  ($Team.id) { $Team    = $Team.ID}
        if ($Channel.id  ) { $Channel = $Channel.ID   }

        try {
            $c = Get-GraphChannel -Channel $Channel -Team $Team
        }
        Catch {
            throw "Could not get the channel" ; return
        }
        if (-not $c)  {throw "Could not get the channel" ; return }
        if ($force -or $PSCmdlet.Shouldprocess($c.displayname, "Delete Channel")) {

            Invoke-GraphRequest -Method "Delete" -Uri "$GraphUri/teams/$Team/channels/$Channel"
            }
        }
}

function New-GraphChannelMessage    {
    <#
      .Synopsis
        Adds a new thread in a channel in Teams.
      .Description
      .Example
        >
        >$General = Get-GraphTeam $newTeam -ChannelName "General"
        >Add-GraphChannelMessage -Channel $General -Content "Project Firebird now has its own channel."
        This adds a message
    #>

    [Cmdletbinding(SupportsShouldprocess=$true, ConfirmImpact='Low')]
    param   (
        #The channel to post to either as an ID or a channel object.
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $Channel,
        #A team object or the ID of the team, if it can't be derived from the channel.
        [ArgumentCompleter([TeamCompleter])]
        $Team,
        #The Message body - text by default, specify -contentType if using HTML
        [Parameter(Mandatory=$true)]
        [String]$Content,
        #The format of the content, text by default , or HTML
        [ValidateSet("Text","HTML")]
        [String]$ContentType = "Text",
        #if Specified the message will be created without prompting.
        [switch]$Force
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        if     ($Channel.Team)             {$teamID    = $Channel.team }
        elseif ($Team.id)                  {$teamID    = $Team.ID}
        elseif ($Team -is [string] -and
                $Team -match $GUIDRegex)   {$teamID    = $Team}
        elseif ($Team -is [string])        {
                $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
        }       #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams

        if     ($Channel.id)               {$channelID = $Channel.ID   }
        elseif ($Channel -is [string] -and
                $Channel -match '@thread') {$channelID = $channel  }
        elseif ($Channel -is [string]) {
                $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
        }

        if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
                  $channelID -is [string] -and $channelID -match '@thread'))  {
            #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
            Write-Warning -Message 'Could not determine the team and channel IDs'; return
        }
        if ($Channel-is [MicrosoftGraphChannel] ) {$c= $Channel}
        else {
            try {$c = Get-GraphChannel -Channel $channelID -Team $teamID }
            catch         {throw "Could not get the channel" ; return}
        }
        if (-not $c)  {throw "Could not get the channel" ; return }
        $webparams = @{ 'Method'      = 'POST'
                        'URI'         = "$GraphUri/teams/$teamID/channels/$channelID/messages" # "https://graph.microsoft.com/beta/teams/$teamID/channels/$channelID/chatThreads"
                        'ContentType' = 'application/json'
                        'AsType'      = ([MicrosoftGraphChatMessage])
                        'ExcludeProperty' = '@odata.context'

        }
        #$Settings = @{ rootMessage = @{body= @{content=$Content;}}}
        #if ($ContentType -eq 'HTML') {$settings.rootMessage.body['contentType'] = 1}
        #else {$settings.rootMessage.body['contentType'] = 2}
        $webparams['body'] = ConvertTo-Json (@{body = @{content=$Content ; contentType = $ContentType}})
        Write-Debug $webparams.body

        if ($force -or $PSCmdlet.Shouldprocess("Create Message")) {
            $result = Invoke-GraphRequest @webparams
            $result.channelIdentity.TeamID = $teamID
            $result.channelIdentity.ChannelId = $channelID
            $result
        }
    }
}

function New-GraphChannelReply      {
    <#
      .Synopsis
        Posts a reply to a message in a Teams channel
    #>

    [Cmdletbinding(SupportsShouldProcess=$true)]
    param   (
        #The Message to reply to as an ID or a message object
        [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)]
        $Message,
        #If Message does not contain the channel, the channel either as an ID or an object containing an ID and possibly the team ID
        $Channel,
        #If the message or channel parameters don't included the team ID, the team either as an ID or an objec containing the ID
        $Team,
        #The Message body - text by default, specify -contentType if using HTML
        [Parameter(Mandatory=$true)]
        [String]$Content,
        #The format of the content, text by default , or HTML
        [ValidateSet("Text","HTML")]
        [String]$ContentType = "Text",
        #Normally the reply is added 'silently'. If passthru is specified, the new message will be returned.
        [Alias('PT')]
        [switch]$Passthru,
        #if Specified the message will be created without prompting.
        [switch]$Force
    )
    $webparams = @{ 'Method'      = 'POST'
                    'ContentType' = 'application/json'
                    'AsType'      = ([MicrosoftGraphChatMessage])
                    'ExcludeProperty' = '@odata.context'
    }
    #region convert the information from the message (and optionally channel and team) into a URI to post to
    if     ($message.ChannelIdentity.TeamId)    {$teamId    = $message.ChannelIdentity.TeamId }
    elseif ($Message.team)                      {$teamid    = $Message.team}
    elseif ($Channel.team)                      {$teamid    = $Channel.team}
    elseif ($Team.id)                           {$teamid    = $team.id}
    elseif ($Team -is [string] -and
            $Team -match $GUIDRegex)            {$teamID    = $Team}
    elseif ($Team -is [string])                 {
            $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
    }       #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams

    if     ($Message.ChannelIdentity.ChannelId) {$channelid = $Message.ChannelIdentity.ChannelId}
    elseif ($Message.channel)                   {$channelid = $Message.channel}
    elseif ($Channel.id)                        {$channelid = $channel.id}
    elseif ($Channel -is [string] -and
            $Channel -match '@thread')          {$channelID = $channel}
    elseif ($Channel -is [string]) {
                $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
    }

    if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
                  $channelID -is [string] -and $channelID -match '@thread'))  {
            #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
            Write-Warning -Message 'Could not determine the team and channel IDs'; return
    }

    if     ($Message.ID)           {$msgID     = $Message.ID}
    elseif ($Message -is [string]) {$msgID     = $Message }
    else   {Write-Warning 'Could not determine the ID for the message.'; return}

    $webparams['uri'] =  "$GraphUri/teams/$teamid/channels/$channelid/Messages/$msgID/replies"
    #endregion

    $webparams['body'] = ConvertTo-Json  @{body= @{content=$Content; 'contentType'=$ContentType}}
    Write-Debug $webparams.body

    if ($force -or $PSCmdlet.Shouldprocess("Post Reply")) {Invoke-GraphRequest @webparams }
}

function Get-GraphChannelReply      {
    <#
      .Synopsis
        Returns replies to messages in Teams channels
      .Description
        Access to channel messages is currently in the BETA API
        It is possible to start a new thread, but not to reply to the thread.
      .Example
        >Get-GraphChannel $General -Messages | Get-GraphChannelReply -PassThru
        The GraphAPI does not return replies when requesting messages
        from a channel in Teams. By piping the messages to Get-GraphChannelReply
        it is possible to get the replies; and if -Passthru is specified
        the messages will returned, followed by their replies.
        So if $General is a channel object, the first message and the its first
        reply might be output like this.

        From Created Isreply Deleted Importance Content
        ---- ------- ------- ------- ---------- -------
        James O'Neill 17/02/2019 11:42 False False normal Project Firebird now has its own channel.
        James O'Neill 17/02/2019 13:06 True False normal And the channel has its own planner

    #>

    [Cmdletbinding()]
    param   (
        #The Message to reply to as an ID or a message object containing an ID (and possibly the team and channel ID)
        [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)]
        $Message,
        #If the Message does not contain the channel, the channel either as an ID or an object containing an ID and possibly the team ID
        $Channel,
        #If the message or channel parameters don't included the team ID, the team either as an ID or an objec containing the ID
        $Team,
        #If specified returns the message, followed by its replies. (Otherwise , only the replies are returned)
        [switch]$PassThru
    )
    process {
        ContextHas -scopes 'ChannelMessage.Read.All' -BreakIfNot
        #region convert the information from the message (and optionally channel and team) into a URI to post to
        if     ($message.ChannelIdentity.TeamId)    {$teamId    = $message.ChannelIdentity.TeamId }
        elseif ($Message.team)                      {$teamid    = $Message.team}
        elseif ($Channel.team)                      {$teamid    = $Channel.team}
        elseif ($Team.id)                           {$teamid    = $team.id}
        elseif ($Team -is [string] -and
                $Team -match $GUIDRegex)            {$teamID    = $Team}
        elseif ($Team -is [string])                 {
                $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
        }        #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams

        if     ($Message.ChannelIdentity.ChannelId) {$channelid = $Message.ChannelIdentity.ChannelId}
        elseif ($Message.channel)                   {$channelid = $Message.channel}
        elseif ($Channel.id)                        {$channelid = $channel.id}
        elseif ($Channel -is [string] -and
                $Channel -match '@thread')          {$channelID = $channel}
        elseif ($Channel -is [string]) {
                    $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
        }

        if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
                        $channelID -is [string] -and $channelID -match '@thread'))  {
                #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
                Write-Warning -Message 'Could not determine the team and channel IDs'; return
        }

        if     ($Message.ID)           {$msgID     = $Message.ID}
        elseif ($Message -is [string]) {$msgID     = $Message }
        else   {Write-Warning 'Could not determine the ID for the message.'; return}


        if ($PassThru -and $Message -is [MicrosoftGraphChatMessage]) {$Message}
        Get-ChannelMessagesByURI -URI "$GraphUri/teams/$teamid/channels/$channelid/Messages/$msgID/replies"
    }
}

function Add-GraphWikiTab           {
    <#
      .Synopsis
        Adds a wiki tab to a channel in teams
      .Example
        >New-GraphWikiTab -Channel $Channel -TabLabel Wiki
        Channel contains an object representing a channel in teams,
        this adds a Wiki to it. The Wiki will need to be initialized
        when the tab is first opened
    #>

    [CmdletBinding(SupportsShouldprocess=$true)]
    param   (
        #An ID or Channel object which may contain the team ID
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $Channel,
        #A team ID, or a team object if the team can't be found from the the channel
        $Team,
        #The label for the tab
        $TabLabel = "Wiki",
        #If specified the tab will be added without prompting for confirmation
        [switch]$Force
    )

    ContextHas -WorkOrSchoolAccount -BreakIfNot
    if     ($Channel.Team)            {$teamID  = $Channel.Team }
    elseif ($Team.id)                 {$teamID  = $Team.id      }
    elseif ($Team -is [string] -and
            $Team -match $GUIDRegex)  {$teamID    = $Team}
    elseif ($Team -is [string])       {
            $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
    }       #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams
    if     ($Channel.id)           {$channelID = $Channel.id }
    elseif ($Channel -is [string] -and $Channel -notmatch '@thread') {
                $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
    }
    elseif ($Channel -is [string]) {$channelID = $channel  }

    if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
                $channelID -is [string] -and $channelID -match '@thread'))  {
        #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
        Write-Warning -Message 'Could not determine the team and channel IDs'; return
    }
    $webparams = @{'Method'          = 'Post'
                   'Uri'             = "$GraphUri/teams/$teamID/channels/$channelID/tabs"
                   'ContentType'     = 'application/json'
                   'AsType'          =  ([MicrosoftGraphTeamsTab])
                   'ExcludeProperty' = '@odata.context'
    }
    $webparams['Body'] = ConvertTo-Json ([ordered]@{
        'displayname'         = $TabLabel
        'teamsApp@odata.bind' = "$GraphUri/appCatalogs/teamsApps/com.microsoft.teamspace.tab.wiki"}
    )

    Write-Debug $webparams.body
    if ($Force -or $PSCmdlet.Shouldprocess($TabLabel,"Create wiki tab")) {Invoke-GraphRequest @webparams}
}

function Add-GraphPlannerTab        {
    <#
      .Synopsis
        Adds a planner tab to a team-channel for a pre-existing plan
      .Description
        This posts to https://graph.microsoft.com/v1.0/teams/{id}/channels/{id}/tabs
        which requires consent to use the Group.ReadWrite.All scope.
      .Example
        >
        >$channel = Get-GraphTeam -ByName accounts -Channels -ChannelName 'year-end'
        >$plan = Get-GraphTeam -ByName accounts -Plans | where title -Like "year end*"
        >Add-GraphPlannerTab -Plan $plan -Channel $channel -TabLabel "Planner"
        The first line gets the 'year-end' channel for the accounts team
        The second gets a plan with tile which matches 'year end'
        and the third creates a tab labelled 'Planner' in the channel for that plan.
    #>

    [CmdletBinding(SupportsShouldProcess=$true)]
    param   (
        #An ID or Plan object for a plan within the team
        [Parameter(Mandatory=$true,Position=0)]
        $Plan,
        #An ID or Channel object for a channel (which may contain the team ID)
        [Parameter(Mandatory=$true,Position=1)]
        $Channel,
        #A team ID, or a team object, if not specified as part of the channel
        $Team,
        #The label for the tab.
        $TabLabel,
        #If Specified the tab will be added without confirming
        $Force
    )
    #region get IDs needed
    ContextHas -WorkOrSchoolAccount -BreakIfNot
    if       ($Channel.Team)            {$teamID    = $Channel.Team }
    elseif   ($Team.id)                 {$teamID    = $Team.id      }
    elseif   ($Team -is [string] -and
            $Team -match $GUIDRegex)  {$teamID    = $Team}
    elseif   ($Team -is [string])       {
            $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
    } #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams
    if       ($Channel.id)              {$channelID = $Channel.id }
    elseif   ($Channel   -is [string] -and $Channel -notmatch '@thread') {
                $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
    }
    elseif   ($Channel   -is [string])  {$channelID = $channel  }

    if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
              $channelID -is [string] -and $channelID -match '@thread'))  {
        #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
        Write-Warning -Message 'Could not determine the team and channel IDs'; return
    }
    if       ($Plan.id)                 {$Plan      = $Plan.id}
    #endregion
    if ((-not $TabLabel) -and $Plan.Title) {
        Write-Verbose -Message "ADD-GRAPHPLANNERTAB: No Tab label was specified, using the Plan title '$($Plan.Title)'"
        $TabLabel = $Plan.Title
    }

    $tabURI = "https://tasks.office.com/{0}/Home/PlannerFrame?page=7&planId={1}" -f $Global:GraphUser, $Plan

    $webparams = @{'Method'          = 'Post'
                   'Uri'             = "$GraphUri/teams/$teamID/channels/$channelID/tabs"
                   'ContentType'     = 'application/json'
                   'AsType'          =  ([MicrosoftGraphTeamsTab])
                   'ExcludeProperty' = '@odata.context'
    }

    $webparams['body'] = ConvertTo-Json ([ordered]@{
        'displayname'         = $TabLabel
        'teamsApp@odata.bind' = "$GraphUri/appCatalogs/teamsApps/com.microsoft.teamspace.tab.planner"
        'configuration' = [ordered]@{
                   'entityId'   = $plan
                   'contentUrl' = $tabURI
                   'websiteUrl' = $tabURI
                   'removeUrl'  = $tabURI
        }
    })
    Write-Debug $webparams.body
    if ($Force -or $PSCmdlet.ShouldProcess($TabLabel,"Add Tab")) {Invoke-GraphRequest @webparams}
}

function Add-GraphOneNoteTab        {
    <#
      .Synopsis
        Adds a tab in a Teams channel for a OneNote section or Notebook
      .Description
        This posts to https://graph.microsoft.com/v1.0/teams/{id}/channels/{id}/tabs
        which requires consent to use the Group.ReadWrite.All scope.
        The Notebook Parameter has an alias of 'Section' and will accept either
        a OneNote Notebook object (or its 'Self' URI - which requires the tab name to be
        set explicitly) or a Section object. If the notebook is specified it opens at the
        first section.
      .Example
        >
        > $section = Get-GraphTeam -ByName accounts -Notebooks | Select-Object -ExpandProperty sections | where displayname -like "FY-19*"
        > $channel = Get-GraphTeam -ByName accounts -Channels -ChannelName 'year-end'
        > Add-GraphOneNoteTab $section $channel -TabLabel "FY-19 Notes"

        The first command gets the Notebook for the Accounts team and finds the "FY-19 Year End" section
        The second command gets the channels for the same team and finds the "Year end" channel
        The Third command creates a tab in the channel named 'FY-19 Notes' which opens the team notebook
        at its 'FY-19 Year End' section.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param   (
        #The Notebook or Section to associate with the tab
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
        [Alias('Section')]
        $Notebook,
        #An ID or Channel object which may contain the team ID; the tab will be created in this channel
        [Parameter(Mandatory=$true, Position=1)]
        $Channel,
        #A team ID, or a team object if the team can't be found from the the channel
        $Team,
        #The label for the tab, if left blank the name of the Notebook or Section will be sued
        $TabLabel,
        #If Specified the tab will be added without pausing for confirmation, this is the default unless $ConfirmPreference has been set.
        $Force
    )
    process {
        ContextHas -scopes 'Group.ReadWrite.All' -BreakIfNot
        #region ensure we have the team , channel and notebook IDs, and a label for the tab
        if       ($Channel.Team)              {$teamID    = $Channel.Team }
        elseif   ($Team    -is [string] -and
                  $Team    -match $GUIDRegex) {$teamID    = $Team}
        elseif   ($Team    -is [string])      {
                  $teamID = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
        }         #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams

        if       ($Channel.id)                {$channelID = $Channel.id }
        elseif   ($Channel -is [string] -and
                $Channel -match '@thread') {$channelID = $channel  }
        elseif   ($Channel -is [string])      {
                $Channelid = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id
        }
        if (-not ($teamID  -is [string] -and   $teamId    -match $GUIDRegex -and
                $channelID -is [string] -and $channelID -match '@thread'))  {
            #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
            Write-Warning -Message 'Could not determine the team and channel IDs'; return
        }
        if       (-not $TabLabel -and
                       $Notebook.displayName) {$TabLabel = $Notebook.displayName}
        elseif   (-not $TabLabel)             {
            Write-warning 'Unable to determin a name for the tab, please specify one explicitly'; return
        }
        #endregion
        if       (-not $Notebook.Id -or
                      ($Notebook -is [MicrosoftGraphOnenoteSection] -and -not
                       $Notebook.ParentNotebook.Id  )) {
            Write-Warning 'Could not determine the notebook ID.'; return
        }
        $webparams = @{
            'Method'          = 'Post'
            'Uri'             = "$GraphUri/teams/$teamID/channels/$channelID/tabs"
            'ContentType'     = 'application/json'
            'AsType'          =  ([MicrosoftGraphTeamsTab])
            'ExcludeProperty' = '@odata.context'
        }
        #This had to be reverse engineered, from a beta version of the API, so if it works past next week, be happy.
        #If the "Notebook" object is actually a section, and it was fetched by one of the module commands (get-GraphTeam -notebook, or get-graphNotebook -section)
        #then $Notebook it will have a a parentNotebook ID. This IF..Else is to make sure we have the real notebook ID, and catch a sectionID if there is one.
        if       ($Notebook.parentNotebook.id) {
                  $ParamsPt2     = '&notebookSource=PickSection&sectionId='+ $Notebook.id
                  $NotebookID    = $Notebook.parentNotebook.id
        }
        else  {   $ParamsPt2     = '&notebookSource=New'
                  $NotebookID    = $Notebook.id }

        #if $Notebook is a section its url will end ?wd=(something). We need to split this off the URL and re-use it. The () need to be unescapted too,
        if       ($Notebook.links.oneNoteWebUrl.href -match '\?(wd=.*$)') {
                  $ParamsPt2    += '&' + ( $Matches[1] -replace '%28','(' -replace '%29',')' )
                  $OnenoteWebUrl = $Notebook.links.oneNoteWebUrl.href  -replace  '\?wd=.*$', ''
        }
        else     {$OnenoteWebUrl = $Notebook.links.oneNoteWebUrl.href}

        #We need the teamsite URL for the team who owns this channel, and the URL to the the Notebook. Both need to be escaped.
        $OnenoteWebUrl  = $OnenoteWebUrl                             -replace "%", "%25" -replace '/','%2F' -replace ':','%3A'
        $siteUrl        = (Get-GraphTeam -Team $Teamid -Site).webUrl -replace "%", "%25" -replace '/','%2F' -replace ':','%3A'

        #Now we need to build up the mother and father of all URIs It contains the ID and URL for the notebook (not section). The Name, the teamsite. And Section specifics if applicable.
        $URIParams      = "?entityid=%7BentityId%7D&subentityid=%7BsubEntityId%7D&auth_upn=%7Bupn%7D&ui={locale}&tenantId={tid}"+
                          "&notebookSelfUrl=https%3A%2F%2Fwww.onenote.com%2Fapi%2Fv1.0%2FmyOrganization%2Fgroups%2F$TeamID%2Fnotes%2Fnotebooks%2F"+ $NotebookID   +
                          "&oneNoteWebUrl=" + $oneNoteWebUrl +
                          "&notebookName="  + [uri]::EscapeDataString( $notebook.displayName ) +
                          "&siteUrl="       + $SiteUrl + $ParamsPt2

        #Now we can create the JSON. Such information as there is can be found at https://docs.microsoft.com/en-us/graph/teams-configuring-builtin-tabs
        $json = ConvertTo-Json ([ordered]@{
                'teamsApp@odata.bind' = "$GraphUri/appCatalogs/teamsApps/0d820ecd-def2-4297-adad-78056cde7c78"
                'displayname'         = $TabLabel
                'configuration'       = [ordered]@{
                    'entityId'        = ((New-Guid).tostring() + "_" +  $Notebook.ID)
                    'contentUrl'      = "https://www.onenote.com/teams/TabContent" + $URIParams
                    'removeUrl'       = "https://www.onenote.com/teams/TabRemove"  + $URIParams
                    'websiteUrl'      = "https://www.onenote.com/teams/TabRedirect?redirectUrl=$oneNoteWebUrl"
                }})
        $webparams['body'] = $json  -replace "\\u0026","&"
        Write-Debug $webparams.body
        if ($Force -or $PSCmdlet.ShouldProcess($TabLabel,"Add Tab")) {Invoke-GraphRequest @webparams }
    }
}

function Add-GraphSharePointTab     {
    <#
      .Synopsis
        Adds a planner tab to a team-channel for sharepoint deurl
      .Description
        This posts to https://graph.microsoft.com/v1.0/teams/{id}/channels/{id}/tabs
        which requires consent to use the Group.ReadWrite.All scope.
      .Example

    #>

    [CmdletBinding(SupportsShouldProcess=$true)]
    param   (
        #An ID or Plan object for a plan within the team
        [Parameter(Mandatory=$true,Position=0,ValueFromPipelineByPropertyName=$true)]
        $WebUrl,
        #The label for the tab by default the displayname for of the list
        [Parameter(Mandatory=$true,Position=1,ValueFromPipelineByPropertyName=$true)]
        [Alias('DisplayName')]
        $TabLabel,
        #The label for the tab.
        [Parameter(Position=2,ValueFromPipelineByPropertyName=$true)]
        #Either a genericList (default) or a documentLibrary
        $Template = 'genericList',
        #An ID or Channel object for a channel (which may contain the team ID)
        [Parameter(Mandatory=$true,Position=3)]
        $Channel,
        #A team ID, or a team object, if not specified as part of the channel
        $Team,
        #If Specified the tab will be added without confirming
        $Force
    )
    process {
        ContextHas -WorkOrSchoolAccount -BreakIfNot
        #region get IDs needed
        if       ($Channel.Team)                {$teamID  = $Channel.Team }
        elseif   ($Team.id)                     {$teamID  = $Team.id      }
        elseif   ($Team      -is [string] -and
                  $Team   -match $GUIDRegex)    {$teamID    = $Team}
        elseif   ($Team      -is [string])      {
                  $teamID   = (Invoke-GraphRequest -Uri "$GraphUri/groups?`$filter=startswith(displayname,'$Team')" -ValueOnly).id
        } #had "ResourceProvisioningOptions eq 'team' and " in the filter but it removed some valid teams
        if       ($Channel.id)                  {$channelID = $Channel.id }
        elseif   ($Channel   -is [string] -and
                  $Channel -notmatch '@thread') {$channelID = (Get-GraphTeam -Team $teamID -Channels -ChannelName $channel).id}
        elseif   ($Channel   -is [string])      {$channelID = $Channel  }

        if (-not ($teamID    -is [string] -and $teamId    -match $GUIDRegex -and
                  $channelID -is [string] -and $channelID -match '@thread'))  {
            #we got zero matches or more than one for a team/channel name, or we got an object without an ID, or an object where the ID wasn't a guid
            Write-Warning -Message 'Could not determine the team and channel IDs'; return
        }
        #endregion

        $webparams = @{
            'Method'          = 'Post'
            'Uri'             = "$GraphUri/teams/$teamID/channels/$channelID/tabs"
            'ContentType'     = 'application/json'
            'AsType'          =  ([MicrosoftGraphTeamsTab])
            'ExcludeProperty' = '@odata.context'
        }
        if ($Template = 'genericList') {
            $webparams['body'] = ConvertTo-Json ([ordered]@{
                'displayname'         = $TabLabel
                'teamsApp@odata.bind' = "$GraphUri/appCatalogs/teamsApps/2a527703-1f6f-4559-a332-d8a7d288cd88"
                'configuration'       = [ordered]@{
                            'entityId'   = ""
                            'contentUrl' =  ($WebUrl -replace '(.*/sites/[^/]+/).*$','$1_layouts/15/teamslogon.aspx?spfx=true&dest=') + [uri]::EscapeDataString($WebUrl)
                            'websiteUrl' = $WebUrl
                            'removeUrl'  = $null
                }
            })
        }
        elseif ($Template = 'genericList') {
            $webparams['body'] = ConvertTo-Json ([ordered]@{
                'displayname'         = $TabLabel
                'teamsApp@odata.bind' = "$GraphUri/appCatalogs/teamsApps/com.microsoft.teamspace.tab.files.sharepoint"
                'configuration'       = [ordered]@{
                            'entityId'   = ""
                            'contentUrl' = $WebUrl
                            'websiteUrl' = $null
                            'removeUrl'  = $null
                }
            })
        }
        else {
            Write-Warning "Cannot handle the template type of '$Template'." ; return
        }
        Write-Debug $webparams.body
        if ($Force -or $PSCmdlet.ShouldProcess($TabLabel,"Add Tab")) {Invoke-GraphRequest @webparams}
    }
}

# Adding tab https://docs.microsoft.com/en-us/graph/api/teamstab-add?view=graph-rest-1.0
# Get-GraphTeamsApp will get the apps but we don't get the ability to configure them
#- often some other things will get called as part of setup and need be reverse engineered. e.g. whiteboard calls another service to get a new whiteboard GUID
function Get-GraphTeamsApp          {
    <#
      .synopsis
        Returns apps from the teams app catalog
    #>

    param   (
        [string]$App
    )
    process {
        ContextHas -scopes 'AppCatalog.Submit', 'AppCatalog.Read.All', 'AppCatalog.ReadWrite.All', 'Directory.Read.All', 'Directory.ReadWrite.All' -BreakIfNot
        $uri = "$GraphUri/appcatalogs/teamsApps"
        if ($App -match $guidRegex) {
            Invoke-GraphRequest "$uri/$App`?`$expand=appdefinitions" -ExcludeProperty '@odata.context'  -AsType ([MicrosoftGraphTeamsApp])
        }
        elseif ($App) {
            $uri += '?$filter=startswith(tolower(displayname),''{0}'')' -f $App.toLower()
            Invoke-GraphRequest $uri  -ValueOnly -AsType ([MicrosoftGraphTeamsApp])  | Sort-Object -Property Displayname
        }
        else   {
            Invoke-GraphRequest $uri   -ValueOnly -AsType ([MicrosoftGraphTeamsApp]) -Headers @{'ConsistencyLevel'='eventual'} | Sort-Object -Property Displayname
        }
    }
}