OGraph.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
###############################################################################################
# Module Variables
###############################################################################################
$ModuleVariableNames = ('OGraphConfiguration','GraphVersion')
$ModuleVariableNames.ForEach( { Set-Variable -Scope Script -Name $_ -Value $null })
$Script:GraphVersion = 'v1.0'

###############################################################################################
# Module Removal
###############################################################################################
#Clean up objects that will exist in the Global Scope due to no fault of our own . . . like PSSessions

$OnRemoveScript = {
  # perform cleanup
  Write-Verbose -Message 'Removing Module Items from Global Scope'
}

$ExecutionContext.SessionState.Module.OnRemove += $OnRemoveScript

<#
.SYNOPSIS
Add Group Member

.DESCRIPTION
Add a group member using its object id or user principal name. If using the later, a lookup is performed with get-oguser to get the Object ID for the user.

Permissions: https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
Parameter description

.PARAMETER UserPrincipalName
Parameter description

.PARAMETER MemberId
Parameter description

.EXAMPLE
Add-OGGroupMember -GroupObjectId 3175b598-0fa0-4002-aebf-bfbf759c94a7 -UserObjectId 3fbabd10-7bbc-410d-ba6c-0ba60e863c30

.NOTES
General notes
#>

Function Add-OGGroupMember {
    [CmdletBinding(DefaultParameterSetName = 'MID')]

    param (
        [Parameter(Mandatory,
            ParameterSetName = 'MID')]
        [Parameter(Mandatory,
            ParameterSetName = 'UPN')]
        $GroupId,
        [Parameter(Mandatory,
            ParameterSetName = 'UPN')]
        $UserPrincipalName,
        [Parameter(Mandatory,
            ParameterSetName = 'MID')]
        $MemberId
    )

    switch ($PSCmdlet.ParameterSetName) {
        'UPN' {
            $MemberId = Get-OGUser -UserPrincipalName $UserPrincipalName
            $MemberId = $MemberId.Id
        }
    }
    $URI = "/$GraphVersion/groups/$GroupID/members/`$ref"
    $Body = [PSCustomObject]@{
        '@odata.id' = "https://graph.microsoft.com/$GraphVersion/directoryObjects/$MemberId"
    }
    $account_params = @{
        Uri    = $URI
        Body   = $Body | ConvertTo-Json
        Method = 'POST'
    }
    Invoke-MgGraphRequest @Account_params
}
<#
.SYNOPSIS
Get API Token from Azure AD app using Access Secret or Certificate Thumprint, then authenticate to graph with the token. Or authenticate using user credentials.

.DESCRIPTION
This function allows easy Authentication to Azure AD application authentication tokens or User Credentials. To get a Azure AD application token, provide the tenant ID, Application ID, and either an access secret or certificate thumbprint. The token with automatically authenticate the session after a valid token is acquired or online credentials are entered. If you have an existing token, paste it into accesstoken.

.PARAMETER ApplicationID
Identifier for the Application Registration to use for connection to the Microsoft Tenant

.PARAMETER TenantId
Identifier for the Microsoft Tenant

.PARAMETER ClientSecret
Client Secret for the Application Registration to be used for client authentication for connection to the Microsoft Tenant

.PARAMETER CertificateThumbprint
Certificat thumbprint of the certificate to be used for client authentiaction for connection to the Microsoft Tenant

.PARAMETER UseDeviceAuthentication
Use device code flow

.PARAMETER Scope
Specify the Microsoft Graph scope(s) to include in the connection context. User must have appropriate permissions and/or be able to consent to the permissions.

.PARAMETER AccessToken
Specify the pre-obtained access code to use for the connection to the Microsoft Tenant

.EXAMPLE
Authenticate to graph with application access secret:
Connect-OGGraph -ApplicationID f3857fc2-d4a5-1427-8f4c-2bdcd0cd9a2d -TenantID 27f1409e-4f28-4115-8ef5-71058ab01821 -AccessSecret Rb4324~JBiAJclWeG1W239CPgKHlChi9l0423jjdg~

.NOTES
General notes
#>

Function Connect-OGGraph
{
    [CmdletBinding(DefaultParameterSetName = 'Interactive')]
    param (

        [Parameter(Mandatory,Parametersetname = 'Secret')]
        [Parameter(Mandatory,Parametersetname = 'Cert')]
        $ApplicationID
        ,
        [Parameter(Mandatory,Parametersetname = 'Secret')]
        [Parameter(Mandatory,Parametersetname = 'Cert')]
        $TenantId
        ,
        [Parameter(Mandatory,Parametersetname = 'Secret')]
        $ClientSecret
        ,
        [Parameter(Mandatory,Parametersetname = 'Cert')]
        $CertificateThumbprint
        ,
        [Parameter(Parametersetname = 'Interactive')]
        [Parameter(Parametersetname = 'DeviceAuth')]
        [string[]]$Scope
        ,
        [Parameter(Mandatory,Parametersetname = 'Token')]
        $AccessToken
        ,
        [Parameter(Mandatory,Parametersetname = 'DeviceAuth')]
        [switch]$UseDeviceAuthentication
    )
    switch ($PSCmdlet.ParameterSetName)
    {
        'Secret'
        {
            $Body = @{
                Grant_Type    = 'client_credentials'
                Scope         = 'https://graph.microsoft.com/.default'
                client_Id     = $ApplicationID
                Client_Secret = $ClientSecret
            }
            $ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method POST -Body $Body
            $script:GraphAPIKey = $ConnectGraph.access_token
            Connect-MgGraph -AccessToken $GraphAPIKey
        }
        'Cert'
        {
            $splat = @{
                ClientID              = $ApplicationID
                TenantId              = $TenantId
                CertificateThumbprint = $CertificateThumbprint
            }
            Connect-MgGraph @splat
        }
        'Interactive'
        {
            switch ($scope.count -ge 1)
            {
                $true
                {
                    Connect-MgGraph -UseDeviceAuthentication -Scopes $Scope
                }
                $false
                {
                    Connect-MgGraph
                }
            }
        }
        'DeviceAuth'
        {
            switch ($scope.count -ge 1)
            {
                $true
                {
                    Connect-MgGraph -UseDeviceAuthentication -Scopes $Scope
                }
                $false
                {
                    Connect-MgGraph -UseDeviceAuthentication
                }
            }

        }
        'Token'
        {
            Connect-MgGraph -AccessToken $AccessToken
        }
    }
}
<#
.SYNOPSIS
Get the current version of the Graph API that OGraph is using

.DESCRIPTION
Get the current version of the Graph API that OGraph is using

.EXAMPLE
Get-OGGraphVersion
#>

Function Get-OGGraphVersion
{
    $Script:GraphVersion
}

<#
.SYNOPSIS
List Calendars for a user or specify a users calendar with the calendars guid.

.DESCRIPTION
List Calendars for a user or specify a users calendar with the calendars guid.

Permissions: https://learn.microsoft.com/en-us/graph/api/user-list-calendars?view=graph-rest-1.0&tabs=http

.PARAMETER UserPrincipalName
Parameter description

.PARAMETER Id
Parameter description

.EXAMPLE
Get-OGCalendar -UserPrincipalName jdoe@contoso.com

.NOTES
General notes
#>

Function Get-OGCalendar {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$UserPrincipalName,
        [Parameter(Mandatory = $false)]$Id
    )
    if (-not [string]::IsNullOrWhiteSpace($id)) {
        $URI = "/$GraphVersion/users/$UserPrincipalName/calendars/$id"
        Get-OGNextPage -uri $URI
    }
    else {
        $URI = "/$GraphVersion/users/$UserPrincipalName/calendars"
        Get-OGNextPage -uri $URI
    }
}
<#
.SYNOPSIS
Get group from Azure AD
.DESCRIPTION
Get group using an Object ID, by searching for a displayname, or getting all groups.

Permissions: https://learn.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
GroupID (guid) for the group

.PARAMETER SearchDisplayName
Get the Group(s) by DisplayName search

.PARAMETER All
Get all Groups from the Microsoft Tenant

.PARAMETER UnifiedAll
Get all Unified Groups from the Microsoft Tenant

.PARAMETER Property
Include the specified group property(ies) in the output

.EXAMPLE
Get a group by Object ID
Get-OGGroup -GroupId 3175b598-0fa0-4002-aebf-bfbf759c94a7

.NOTES
General notes
#>

Function Get-OGGroup
{
    [CmdletBinding(DefaultParameterSetName = 'OID')]
    param (

        [Parameter(ParameterSetName = 'OID')]
        $GroupId
        ,
        [Parameter(ParameterSetName = 'Search')]
        $SearchDisplayName
        ,
        [Parameter(ParameterSetName = 'All')]
        [Switch]$All
        ,
        [Parameter(ParameterSetName = 'UnifiedAll')]
        [Switch]$UnifiedAll
        ,
        [Parameter()]
        [string[]]$Property

    )
    $IncludeAttributes =[System.Collections.Generic.List[string]]@('classification', 'createdByAppId', 'createdDateTime', 'deletedDateTime', 'description', 'displayName', 'expirationDateTime', 'groupTypes', 'id', 'infoCatalogs', 'isAssignableToRole', 'isManagementRestricted', 'mail', 'mailEnabled', 'mailNickname', 'membershipRule', 'membershipRuleProcessingState', 'onPremisesDomainName', 'onPremisesLastSyncDateTime', 'onPremisesNetBiosName', 'onPremisesProvisioningErrors', 'onPremisesSamAccountName', 'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'organizationId', 'preferredDataLocation', 'preferredLanguage', 'proxyAddresses', 'renewedDateTime', 'resourceBehaviorOptions', 'resourceProvisioningOptions', 'securityEnabled', 'securityIdentifier', 'theme', 'visibility', 'writebackConfiguration')
    $IncludeAttributeString = $($($includeAttributes; $Property) | Sort-Object -unique) -join ','
    switch ($PSCmdlet.ParameterSetName)
    {
        'OID'
        {
            $URI = "/$GraphVersion/groups/$($GroupId)?`$select=$($IncludeAttributeString)"
            get-ognextpage -uri $uri
        }
        'Search'
        {
            $URI = '/' + $GraphVersion + '/groups?$search="displayName:' + $SearchDisplayName + '"&$select=' + $IncludeAttributeString
            Get-OGNextPage -uri $URI -Filter
        }
        'All'
        {
            $URI = "/$GraphVersion/groups?`$select=$($IncludeAttributeString)"
            Get-OGNextPage -Uri $URI
        }
        'UnifiedAll'
        {
            $URI = "/$GraphVersion/groups?`$filter=groupTypes/any(c:c+eq+'Unified')&`$select=$($IncludeAttributeString)"
            Get-OGNextPage -Uri $URI -Filter
        }
    }
}
<#
.SYNOPSIS
Get group drive from Microsoft Graph
.DESCRIPTION
Get group drive using Group Object ID

Permissions: https://learn.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
GroupID (guid) for the group

.EXAMPLE
Get a group drive by Object ID
Get-OGGroupDrive -GroupId 3175b598-0fa0-4002-aebf-bfbf759c94a7

    GroupID : 3175b598-0fa0-4002-aebf-bfbf759c94a7
    DriveName : Documents
    DriveURL : https://contoso.sharepoint.com/teams/contosoteam/Shared%20Documents
    DriveID : b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd
    driveType : documentLibrary
    SiteURL : https://contoso.sharepoint.com/teams/contosoteam
    createdDateTime : 10/24/2022 05:12:09 AM
    lastModifiedDateTime : 11/21/2022 02:37:01 PM
    quotaTotal : 1073741824000
    quotaUsed : 1479181
    quotaRemaining : 1479181
    quotaDeleted : 0
    quotaState : normal

#>

Function Get-OGGroupDrive
{
    [CmdletBinding()]
    param (

        [Parameter()]
        [guid]$GroupId
    )

    $URI = "/$GraphVersion/groups/$($GroupId)/drive/"

    $Result =  get-ognextpage -uri $uri

    $Result | Select-Object -Property @{n='GroupID'; e={$GroupId}},
    @{n='DriveName'; e={$_.name}},
    @{n='DriveURL'; e={$_.webUrl}},
    @{n='DriveID'; e={$_.id}},
    'driveType',
    @{n='SiteURL'; e={$_.webUrl.substring(0, $_.weburl.LastIndexOf('/'))}},
    'createdDateTime',
    'lastModifiedDateTime',
    @{n='quotaTotal'; e={$_.quota.total}},
    @{n='quotaUsed'; e={$_.quota.used}},
    @{n='quotaRemaining'; e={$_.quota.used}},
    @{n='quotaDeleted'; e={$_.quota.Deleted}},
    @{n='quotaState'; e={$_.quota.state}}

}
<#
.SYNOPSIS
Get the license skus applied by a group

.DESCRIPTION
Gets the license skus applied by a group and any disabled service plans of those skus

Permissions: https://learn.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0&tabs=http

.EXAMPLE
Get-OGGroupLicense -GroupId f6557fc2-d4a5-4266-8f4c-2bdcd0cd9a2d

.NOTES
General notes
#>

Function Get-OGGroupLicense
{
    [CmdletBinding()]
    param (
        # GroupID (guid) for the Group
        [Parameter(Mandatory)]$GroupId
        ,
        # Specify if you want to include the SKU Display Name (Friendly Name) in the output object
        [parameter()]
        [switch]$IncludeDisplayName
<# ,
        [parameter()]
        [ValidateLength(1,1)]
        [string]$ServicePlanDelimiter = ';' #>

        ,
        # Specify if you want to pass through the GroupID to the output object as an attribute
        [parameter()]
        [switch]$PassthruGroupID
    )

    $ReadableHash = @{}
    switch ($IncludeDisplayName)
    {
        $true
        {
            $skusReadable = Get-OGReadableSku
            foreach ($sR in $skusReadable)
            {
                $ReadableHash[$sR.GUID] = $sR.Product_Display_Name
                $ReadableHash[$sR.Service_Plan_Id] = $sR.Service_Plans_Included_Friendly_Names
            }
        }
    }
    $URI = "/$GraphVersion/groups/$GroupId/assignedLicenses"
    $rawSku = @(Get-OGNextPage -uri $Uri)
    if ($PassthruGroupID) {
        $rawSku = @($rawSku | Select-Object -Property @{n='GroupID';e={$GroupID}},*)
    }
    foreach ($s in $rawSku)
    {
        $s | Select-Object -Property *,
        @{n='skuDisplayName';e = {$ReadableHash[$s.skuid]}}
        #@{n='servicePlanNames';e= {$s.ServicePlans.foreach({$_.ServicePlanName}) -join $ServicePlanDelimiter}},
        #@{n='servicePlanDisplayNames'; e= {$s.ServicePlans.foreach({$ReadableHash[$_.ServicePlanID]}).where({$null -ne $_}) -join $ServicePlanDelimiter}}
    }
}
<#
.SYNOPSIS
Report all Enabled and Disabled skus and service plans applied by a group

.DESCRIPTION
Report all Enabled and Disabled skus and service plans applied by a group

Permissions: https://learn.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
GroupID (guid) for the group for which to report licensing details.

.PARAMETER All
Includes all groups that have a license assignment.

.PARAMETER IncludeDisplayName
Includes "human readable" Display Names for skus and service plans.

.EXAMPLE
Get-OGGroupLicenseReport -GroupId f6557fc2-d4a5-4266-8f4c-2bdcd0cd9a2d

.NOTES
General notes
#>

Function Get-OGGroupLicenseReport
{

    [CmdletBinding(DefaultParameterSetName = 'Single')]
    param (
        [Parameter(Mandatory, ParameterSetName = 'Single')]
        $GroupId,
        [Parameter(Mandatory, ParameterSetName = 'All')]
        [switch]$All,
        [Parameter()]
        [switch]$IncludeDisplayName
    )
    switch ($PSCmdlet.ParameterSetName)
    {

        'All'
        {
            $groups = @(Get-OGGroup -All -Property assignedLicenses).where({$_.assignedLicenses.count -ge 1})
            $getOGGLRParams = @{IncludeDisplayName = $IncludeDisplayName}
            $groups.foreach({ Get-OGGroupLicenseReport -GroupId $_.id @getOGGLRParams})
        }

        'Single'
        {
            $ReadableHash = @{}
            switch ($IncludeDisplayName)
            {
                $true
                {
                    $skusReadable = Get-OGReadableSku
                    foreach ($sR in $skusReadable)
                    {
                        $ReadableHash[$sR.GUID] = $sR.Product_Display_Name
                        $ReadableHash[$sR.Service_Plan_Id] = $sR.Service_Plans_Included_Friendly_Names
                    }
                }
            }
            $skus = Get-OGSku
            $group = Get-OGGroup -GroupId $groupid
            $skuHash = @{} #hashtable to be populated with key SkuID and value SKU detail object
            $spHash = @{} #hashtable to be populated with key service plan ID and value service plan detail object
            $spPerSku = @{} #hasthable to be populated with key SkuID and value ServicePlanIDs collection
            foreach ($s in $skus)
            {
                $sku = [PSCustomObject]@{
                    type                          = 'Sku'
                    skuDisplayName                = $ReadableHash[$s.skuid]
                    skuName                       = $s.skuPartNumber
                    prepaidUnitsEnabled           = $s.prepaidUnitsEnabled
                    consumedUnits                 = $s.consumedUnits
                    nonConsumedUnits              = $s.nonConsumedUnits
                    skuAppliesTo                  = $s.appliesTo
                    skuId                         = $s.skuId
                    servicePlanName               = $null
                    servicePlanId                 = $null
                    servicePlanProvisioningStatus = $null
                    servicePlanAppliesTo          = $null
                }
                $skuHash[$sku.skuId] = $Sku
                $splans = @($s.servicePlans)
                foreach ($sp in $splans)
                {
                    $servicePlan = [PSCustomObject]@{
                        type                          = 'ServicePlan'
                        skuDisplayName                = $ReadableHash[$s.skuid]
                        skuName                       = $s.skuPartNumber
                        #skuPrepaidUnits = $s.prepaidUnits
                        skuPrepaidUnitsEnabled        = $s.prepaidUnits.Enabled
                        skuConsumedUnits              = $s.consumedUnits
                        skuNonConsumedUnits           = $sku.nonConsumedUnits
                        skuAppliesTo                  = $s.appliesTo
                        skuId                         = $s.skuId
                        servicePlanDisplayName        = $ReadableHash[$sp.servicePlanId]
                        servicePlanName               = $sp.servicePlanName
                        servicePlanId                 = $sp.servicePlanId
                        servicePlanProvisioningStatus = $sp.provisioningStatus
                        servicePlanAppliesTo          = $sp.appliesTo
                    }
                    $spHash[$servicePlan.servicePlanId + '_' + $sku.skuID] = $servicePlan
                }
                $spPerSku[$s.skuid] = $splans.servicePlanId
            }
            $groupLicense = Get-OGGroupLicense -GroupId $GroupId
            $outputProperties = @(
                @{Name = 'groupId'; Expression = { $group.id } }
                @{Name = 'groupDisplayName'; Expression = { $group.DisplayName } }
                @{Name = 'type'; Expression = { 'ServicePlanPerSku' } }
                'skuDisplayName'
                'skuName'
                'skuId'
                'skuPrepaidUnitsEnabled'
                'skuConsumedUnits'
                'skuNonConsumedUnits'
                'skuAppliesTo'
                'servicePlanDisplayName'
                'servicePlanName'
                'servicePlanId'
                'servicePlanProvisioningStatus'
                'servicePlanAppliesTo'
                @{Name = 'servicePlanIsEnabled'; Expression = { $_.serviceplanid -notin $groupLicense.disabledPlans } }
            )

            @($grouplicense.skuid).foreach({
                    $gskuid = $_
                    $gsp = @($spPerSku[$gskuid])
                    $gsp.foreach({ $spHash[$_ + '_' + $gskuid] })
                }) | Select-Object -ExcludeProperty type -Property $outputProperties
        }
    }
}
<#
.SYNOPSIS
Get calendar events for a group

.DESCRIPTION
Get calendar events for a group or provide a filter queary to filter the results.
NOTE: Delegated Permission Only
Permissions: https://learn.microsoft.com/en-us/graph/api/group-get-event?view=graph-rest-1.0&tabs=http
.PARAMETER GroupId
GroupID (guid) for the group

.PARAMETER Filter
Parameter description

.EXAMPLE
Get all calendar events for a group
Get-OGGroupEvent -GroupId 3fbabd10-7bbc-410d-ba6c-0ba60e863c30

.NOTES
General notes
#>

Function Get-OGGroupEvent
{

    param (
        [Parameter(Mandatory = $True)]$GroupId,
        [Parameter(Mandatory = $False)]$Filter
    )
    if ($filter)
    {

        $URI = "/$GraphVersion/groups/$GroupId/events?`$filter=$filter"
        Get-OGNextPage -URI $URI
    }
    else
    {
        $URI = "/$GraphVersion/groups/$GroupId/events"
        Get-OGNextPage -URI $URI
    }

}

<#
.SYNOPSIS
Get Members of a Group in Azure AD

.DESCRIPTION
Get Members of a Group in Azure AD

Permissions: https://learn.microsoft.com/en-us/graph/api/group-list?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
GroupID (guid) for the group

.EXAMPLE
Get-OGGroupMember -GroupId 3175b598-0fa0-4002-aebf-bfbf759c94a7

.NOTES
General notes
#>

Function Get-OGGroupMember
{

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$GroupId
    )
    $URI = "/$GraphVersion/groups/$GroupId/members"
    Get-OGNextPage -uri $URI

}
<#
.SYNOPSIS
Get specified or all Sharepoint Online Sites in a tenant

.DESCRIPTION
Get specified or all Sharepoint Online Sites in a tenant

Permissions: https://learn.microsoft.com/en-us/graph/api/site-get?view=graph-rest-1.0&tabs=http

.PARAMETER SiteId
SharePoint Site Identifier

.PARAMETER SiteURL
SharePoint Site URL

.PARAMETER All
Get all SharePoint Sites for the connected tenant

.PARAMETER IncludePersonalSites
Include OneDrive for Business Sites in the results

.EXAMPLE
Get-OGSite -SiteId f232e745-0801-4705-beb6-4d9880fc92b4

.NOTES
General notes
#>

Function Get-OGSite {

    [CmdletBinding(DefaultParameterSetName = 'SID')]
    Param(
        [Parameter(Mandatory,
            ParameterSetName = 'SID')]$SiteId,
        [Parameter(Mandatory,
            ParameterSetName = 'URL')]$SiteURL,
        [Parameter(Mandatory,
            ParameterSetName = 'All')][Switch]$All,
        [Parameter(Mandatory = $False,
            ParameterSetName = 'All')][Switch]$IncludePersonalSites
    )
    switch ($PSCmdlet.ParameterSetName) {
        'SID' {
            $account_params = @{
                Uri         = "/$GraphVersion/sites/$SiteId"
                Method      = 'GET'
                OutputType  = 'PSObject'
                ContentType = 'application/json'
            }
            Invoke-MgGraphRequest @Account_params
        }
        'URL' {
        $SiteURI = [uri]::new($SiteURL)

            $account_params = @{
                Uri         = "/$GraphVersion/sites/$($SiteURI.Host):/$($SiteURI.LocalPath)"
                Method      = 'GET'
                OutputType  = 'PSObject'
                ContentType = 'application/json'
            }
            Invoke-MgGraphRequest @Account_params
        }
        'All' {
            $URI = "/$GraphVersion/sites/?$search=*"
            $allResults = Get-OGNextPage -uri $URI
            switch ($IncludePersonalSites) {
                True { $allResults }
                False { $allResults | Where-Object WebUrl -NotLike '*/personal/*' }
            }
        }
    }
}
<#
.SYNOPSIS
Get the lists in a Sharepoint Online Site

.DESCRIPTION
Get the lists in a Sharepoint Online Site

Permissions: https://learn.microsoft.com/en-us/graph/api/site-get?view=graph-rest-1.0&tabs=http
.PARAMETER SiteId
SharePoitn Site Identifier

.EXAMPLE
Get-OGSiteList -SiteId b767d342-3712-492a-94dc-504304cb8412

.NOTES
General notes
#>

Function Get-OGSiteList {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$SiteId
    )
    $URI = "/$GraphVersion/sites/$SiteId/lists"
    Get-OGNextPage -uri $URI

}

<#
.SYNOPSIS
Get columns contained in an SPO site list

.DESCRIPTION
Get columns contained in an SPO site list

Permissions: https://learn.microsoft.com/en-us/graph/api/site-get?view=graph-rest-1.0&tabs=http
.PARAMETER SiteId
SharePoint Site Identifier

.PARAMETER ListId
SharePoint List Identifier

.EXAMPLE
Get-OGSiteListColumn -SiteId b767d342-3712-492a-94dc-504304cb8412 -ListId c1e7d5b3-ed9e-409e-a956-9d77df7c1ec3

.NOTES
General notes
#>


Function Get-OGSiteListColumn {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$SiteId
        ,
        [Parameter(Mandatory)]$ListId
    )

    $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/Columns"
    Get-OGNextPage -uri $URI

}

<#
.SYNOPSIS
Get items in a SPO List

.DESCRIPTION
Get items in a SPO List

Permissions: https://learn.microsoft.com/en-us/graph/api/site-get?view=graph-rest-1.0&tabs=http
.PARAMETER SiteId
SharePoint Site Identifier

.PARAMETER ListId
SharePoint List Identifier

.PARAMETER ItemId
SharePoint List Item Identifier

.EXAMPLE
Get-OGSiteListItem -SiteId a3299706-eac5-46a1-b5eb-5709bea18e89 -ListId 79aafc35-e805-491c-bf19-f0b6c28b6be0
.NOTES
General notes
#>

Function Get-OGSiteListItem {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$SiteId,
        [Parameter(Mandatory)]$ListId,
        [Parameter(Mandatory = $false)]$ItemId
    )
    if ($ItemId) {
        $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items?expand=fields"
        $response = Get-OGNextPage -uri $URI | Where-Object id -EQ $ItemId
        $response.fields
    }
    else {
        $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items?expand=fields"
        $response = Get-OGNextPage -uri $URI
        $response.fields
    }

}

<#
.SYNOPSIS
Get an items version history

.DESCRIPTION
Get an items version history by specifying the site ID, list ID, and item ID

Permissions: https://learn.microsoft.com/en-us/graph/api/listitem-list-versions?view=graph-rest-1.0&tabs=http
.PARAMETER SiteId
Parameter description

.PARAMETER ListId
Parameter description

.PARAMETER ItemId
Parameter description

.EXAMPLE
Get-OGSiteListItemVersion -SiteId a3299706-eac5-46a1-b5eb-5709bea18e89 -ListId 79aafc35-e805-491c-bf19-f0b6c28b6be0
.NOTES
General notes
#>

Function Get-OGSiteListItemVersion {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$SiteId,
        [Parameter(Mandatory)]$ListId,
        [Parameter(Mandatory)]$ItemId
    )
    $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items/$ItemId/versions"
    $response = Get-OGNextPage -uri $URI
    $response.fields
}


<#
.SYNOPSIS
REcursive Helper function for simplifying graph api requests including next page functionality

.DESCRIPTION
Recursive Helper function for simplifying graph api requests including next page functionality.

.PARAMETER URI
Parameter description

.PARAMETER Filter
Parameter description

.EXAMPLE
Get-OGNextpage -URI "/v1.0/users"

.NOTES
General notes
#>

Function Get-OGNextPage {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True)][string]$URI,
        [Parameter(Mandatory = $False)][Switch]$Filter
    )
    $account_params = @{
        URI         = $URI
        Method      = 'GET'
        OutputType  = 'PSObject'
        ContentType = 'application/json'
    }
    switch ($filter) {
        $true {
            $account_params.add('Headers', @{})
            $account_params.Headers.add('ConsistencyLevel', 'eventual')
        }
    }
    $Result = Invoke-MgGraphRequest @Account_params
    switch ($null -ne $Result.value) {
        $true {
            $Result.value
        }
        $False {
            $Result | Select-Object -ExcludeProperty '@odata.*'
        }
    }
    if ($result.'@odata.nextlink') {
        Get-OGNextPage -Uri $result.'@odata.nextlink'
    }
}
<#
.SYNOPSIS
Provide human readable description to M365 Service Plans by downloading the csv in the Microsoft Docs reference.

.DESCRIPTION
Provide human readable description to M365 Service Plans by downloading the csv in the Microsoft Docs reference. If the CSV fails to download a local copy will be used for the output. If the download is successful, the local copy will be updated.

.PARAMETER StoreCSV
Stores the readable sku csv from Microsoft in the Module folder.

.EXAMPLE
Get-OGReadableSku



.NOTES

#>

function Get-OGReadableSku
{
    [CmdletBinding()]
    param (
        [switch]$StoreCSV
    )

    $PreDownloadedCSV = Join-Path -Path $PSScriptRoot -ChildPath 'OGReadableSku.csv'
    switch (Test-Path -Path $PreDownloadedCSV -Type Leaf)
    {
        $True
        {
            switch ($StoreCSV)
            {
                $true
                {
                    # add a refresh option here (rework flow or create separate function for storing)
                }
                $False
                {
                    Import-Csv $PreDownloadedCSV
                }
            }
        }
        $False
        {
            try
            {
                $temp = Get-PSDrive -Name 'Temp'
                $TempPath = Join-Path -Path $temp.Root -ChildPath 'OGReadableSku.csv'
                $url = 'https://download.microsoft.com/download/e/3/e/e3e9faf2-f28b-490a-9ada-c6089a1fc5b0/Product%20names%20and%20service%20plan%20identifiers%20for%20licensing.csv'
                Invoke-WebRequest -Uri $url -OutFile $TempPath
                switch ($StoreCSV)
                {
                    $True
                    {
                        Move-Item -Path $TempPath -Destination $PreDownloadedCSV -Force -Confirm:$false
                    }
                    $False
                    {
                        Import-Csv $TempPath
                    }
                }
            }
            catch
            {
                Out-Null
            }
        }
    }
}
<#
.SYNOPSIS
Get Skus available in the connected Microsoft tenant

.DESCRIPTION
Gets Skus available in the connected Microsoft Tenant and allows the inclusion of "human readable" DisplayNames.

.PARAMETER IncludeDisplayName
Includes "human readable" display names in the output for both skus and serviceplans.

.PARAMETER ServicePlanDelimiter
Specify the delimiter for the ServicePlanNames and ServicePlanDisplayNames. Defaults to ";".

.EXAMPLE
Get-OGSku

.NOTES
Permissions Required: https://learn.microsoft.com/en-us/graph/api/subscribedsku-list?view=graph-rest-1.0&tabs=http
#>

Function Get-OGSku
{
    [CmdletBinding()]
    param(
        [switch]$IncludeDisplayName
        ,
        [parameter()]
        [ValidateLength(1,1)]
        [string]$ServicePlanDelimiter = ';'
    )

    $Uri = "/$GraphVersion/subscribedSkus"
    $ReadableHash = @{}
    $rawSku = get-ognextpage -uri $Uri
    switch ($IncludeDisplayName)
    {
        $true
        {
            $skusReadable = Get-OGReadableSku
            foreach ($sR in $skusReadable)
            {
                $ReadableHash[$sR.GUID] = $sR.Product_Display_Name
                $ReadableHash[$sR.Service_Plan_Id] = $sR.Service_Plans_Included_Friendly_Names
            }
        }
    }

    foreach ($s in $rawSku)
    {
        $s | Select-Object -Property *,
        @{n='prepaidUnitsEnabled';e= {$_.prepaidUnits.enabled}},
        @{n='nonConsumedUnits';e= {$($s.prepaidUnits.Enabled - $s.consumedUnits)}},
        @{n='skuDisplayName';e = {$ReadableHash[$s.skuid]}},
        @{n='servicePlanIDs';e= {$s.ServicePlans.foreach({$_.ServicePlanID}) -join $ServicePlanDelimiter}},
        @{n='servicePlanNames';e= {$s.ServicePlans.foreach({$_.ServicePlanName}) -join $ServicePlanDelimiter}},
        @{n='servicePlanDisplayNames'; e= {$s.ServicePlans.foreach({$ReadableHash[$_.ServicePlanID]}).where({$null -ne $_}) -join $ServicePlanDelimiter}}
    }
}
<#
.SYNOPSIS
Get users from Azure AD

.DESCRIPTION
Get users from Azure AD

Permissions: https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http
.PARAMETER UserPrincipalName
Get Users by userprincipalname

.PARAMETER SearchDisplayName
Search for users by displayname

.PARAMETER All
Get all users in tenant

.PARAMETER Property
Select additional properties of a user

.EXAMPLE
Get-OGUser -UserPrincipalName test@testaccount.onmicrosoft.com

.NOTES
General notes
#>

Function Get-OGUser {

    [CmdletBinding(DefaultParameterSetName = 'UPN')]
    param (
        [Parameter(ParameterSetName = 'UPN')]$UserPrincipalName,
        [Parameter(ParameterSetName = 'Search')]$SearchDisplayName,
        [Parameter(ParameterSetName = 'All')]
        [Switch]$All,
        [Parameter()]
        [string[]]$Property
    )
    $includeAttributes = 'businessPhones', 'displayName', 'givenName', 'id', 'jobTitle', 'mail', 'mobilePhone', 'officeLocation', 'preferredLanguage', 'surname', 'userPrincipalName'
    $IncludeAttributeString = $($($includeAttributes; $Property) | Sort-Object -unique) -join ','
    switch ($PSCmdlet.ParameterSetName) {
        'UPN' {
            $URI = "/$GraphVersion/users/$($userprincipalname)?`$select=$($IncludeAttributeString)"
            Get-OGNextPage -Uri $URI
        }
        'Search' {
            $URI = "/$GraphVersion/users?`$select=$($IncludeAttributeString)`$search=`"displayName:$SearchDisplayName`""
            Get-OGNextPage -uri $URI -filter
        }
        'All' {
            $URI = "/$GraphVersion/users?`$select=$($IncludeAttributeString)"
            Get-OGNextPage -Uri $URI
        }
    }
}
<#
.SYNOPSIS
Get user OneDrive Meta information

.DESCRIPTION
Get user OneDrive Meta information

Permissions: https://learn.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0&tabs=http
.PARAMETER UserPrincipalName
Userprincipalname or ID for lookup

.EXAMPLE
Get-OGUserDrive -userprincipalname test.user@domain.com
.NOTES
General notes
#>

Function Get-OGUserDrive {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]$UserPrincipalName
    )
    $URI = "/$GraphVersion/users/$userprincipalname/drive"
    Get-OGNextPage -uri $URI
}
<#
.SYNOPSIS
Get calendar events for a user

.DESCRIPTION
Get calendar events for a user or provide a filter queary to filter the results.

Permissions: https://learn.microsoft.com/en-us/graph/api/user-list-events?view=graph-rest-1.0&tabs=http
.PARAMETER UserPrincipalName
Parameter description

.PARAMETER Filter
Parameter description

.EXAMPLE
Get all calendar events for a group
Get-OGUserEvent -GroupId 3fbabd10-7bbc-410d-ba6c-0ba60e863c30

.NOTES
General notes
#>

Function Get-OGUserEvent {
    param (
        [Parameter(Mandatory = $True)]$UserPrincipalName,
        [Parameter(Mandatory = $False)]$Filter
    )
    if ($filter) {
        $URI = "/$GraphVersion/users/$userprincipalname/events?`$filter=$filter"
        Get-OGNextPage -URI $URI -Filter
    }
    else {
        $URI = "/$GraphVersion/users/$userprincipalname/events"
        Get-OGNextPage -URI $URI
    }
}
<#
.SYNOPSIS
Get Azure AD skus for individual user

.DESCRIPTION
Get Azure AD skus for individual user

Permissions: https://learn.microsoft.com/en-us/graph/api/user-list-licensedetails?view=graph-rest-1.0&tabs=http

.EXAMPLE
Get-OGUserSku -UserPrincipalName jdoe@contoso.com

.NOTES
General notes
#>

Function Get-OGUserSku {
    [CmdletBinding()]
    param (
        #Specify the UserPrincipalName for the user
        [Parameter(Mandatory)]$UserPrincipalName
        ,
        # Specify whether to include the SKU and ServicePlan Display Names (Friendly Names) in the output object(s)
        [parameter()]
        [switch]$IncludeDisplayName
        ,
        # Specify the delimeter to use betwen Service Plan items in the output object
        [parameter()]
        [ValidateLength(1,1)]
        [string]$ServicePlanDelimiter = ';'
        ,
        # Specify whether to pass through the UserPrincipalName to the output object at an attribute of the output
        [parameter()]
        [alias('PassthruUPN')]
        [switch]$PassthruUserPrincipalName
    )

    $ReadableHash = @{}
    switch ($IncludeDisplayName)
    {
        $true
        {
            $skusReadable = Get-OGReadableSku
            foreach ($sR in $skusReadable)
            {
                $ReadableHash[$sR.GUID] = $sR.Product_Display_Name
                $ReadableHash[$sR.Service_Plan_Id] = $sR.Service_Plans_Included_Friendly_Names
            }
        }
    }

    $Uri = "$GraphVersion/Users/$($UserPrincipalName)/licenseDetails"
    $rawSku = Get-OGNextPage -uri $Uri
    if ($PassthruUserPrincipalName) {
        $rawSku = $rawSku | Select-Object -Property @{n='UserPrincipalName';e={$UserPrincipalName}},*
    }
    foreach ($s in $rawSku)
    {
        $s | Select-Object -Property *,
        @{n='skuDisplayName';e = {$ReadableHash[$s.skuid]}},
        @{n='servicePlanNames';e= {$s.ServicePlans.foreach({$_.ServicePlanName}) -join $ServicePlanDelimiter}},
        @{n='servicePlanDisplayNames'; e= {$s.ServicePlans.foreach({$ReadableHash[$_.ServicePlanID]}).where({$null -ne $_}) -join $ServicePlanDelimiter}}
    }
}
<#
.SYNOPSIS
 Add new item to a SharePoint list
.DESCRIPTION
Create a SharePoint Online list item by providing the SharePoint site ID, the List ID, and the values of the fields to be added in a hash table.
Permissions: https://learn.microsoft.com/en-us/graph/api/listitem-create?view=graph-rest-1.0&tabs=http
.PARAMETER SiteId
SharePoint Site Identifier
.PARAMETER ListId
SharePoint List Identifier
.PARAMETER Fields
Hashtable of item fields and values to include in the new SharePoint List Item
.EXAMPLE
$fields = @{
    field_1 = "Sample String"
}
New-OGSiteListItem -SiteId 26776db6-ffd1-4e58-a6bf-851d6302733a -ListId 26f11389-ffd1-4e24-a7h1-85af93422733a -Fields $fields


.NOTES
General notes
#>

function New-OGSiteListItem {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory)]
        [String]$SiteId
        ,
        [Parameter(Mandatory)]
        [String]$ListId
        ,
        [Parameter(Mandatory)]
        [hashtable]$Fields
    )
    $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items"
    $body = @{fields = $Fields }
    $account_params = @{
        URI         = $URI
        body        = $body | ConvertTo-Json -Depth 5
        Method      = 'POST'
        ContentType = 'application/json'
    }
    if ($PSCmdlet.ShouldProcess($ItemID,'POST'))
    {
        Invoke-MgGraphRequest @Account_params
    }
}
<#
.SYNOPSIS
Remove member from Azure AD group membership

.DESCRIPTION
Remove member from Azure AD group membership

Permissions: https://learn.microsoft.com/en-us/graph/api/group-delete-members?view=graph-rest-1.0&tabs=http

.PARAMETER GroupId
Parameter description

.PARAMETER UserPrincipalName
Parameter description

.PARAMETER MemberId
Parameter description

.EXAMPLE
Remove-OGGroupMember -ObjectId a3299706-eac5-46a1-b5eb-5709bea18e89 -MemberId b767d342-3712-492a-94dc-504304cb8412

.NOTES
General notes
#>

Function Remove-OGGroupMember {

    [CmdletBinding(DefaultParameterSetName = 'MID', SupportsShouldProcess)]
    param (
        [Parameter(Mandatory,
            ParameterSetName = 'MID')]
        [Parameter(Mandatory,
            ParameterSetName = 'UPN')]
        $GroupId,
        [Parameter(Mandatory,
            ParameterSetName = 'UPN')]
        $UserPrincipalName,
        [Parameter(Mandatory,
            ParameterSetName = 'MID')]
        $MemberId
    )
    switch ($PSCmdlet.ParameterSetName) {
        'UPN' {
            $MemberId = Get-OGUser -UserPrincipalName $UserPrincipalName
            $MemberId = $MemberId.Id
        }
    }
    $URI = "/$GraphVersion/groups/$GroupId/members/$MemberId/`$ref"
    $account_params = @{
        Uri    = $URI
        Method = 'DELETE'
    }
    if ($PSCmdlet.ShouldProcess($GroupID, "remove member $($UserPrincipalName)$($MemberId)")) {
        Invoke-MgGraphRequest @Account_params
    }
}
<#
.SYNOPSIS
Delete an item in a SharePoint Online list

.DESCRIPTION
Delete a SharePoint Online list item by providing the SharePoint site ID, the List ID, and the ID of the item to be deleted.

Permissions: https://learn.microsoft.com/en-us/graph/api/listitem-delete?view=graph-rest-1.0&tabs=http

.EXAMPLE
Remove-OGSiteListItem -SiteId 26776db6-ffd1-4e58-a6bf-851d6302733a -ListId 26f11389-ffd1-4e24-a7h1-85af93422733a -ItemId 1234

#>

function Remove-OGSiteListItem {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        #SharePoint Site Identifier
        [Parameter(Mandatory)]
        $SiteId
        ,
        #SharePoint List Identifier
        [Parameter(Mandatory)]
        $ListId
        ,
        #SharePoint List Item Identifier
        [Parameter(Mandatory)]
        $ItemId
    )
    $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items/$ItemId"
    $account_params = @{
        URI         = $URI
        Method      = 'DELETE'
        ContentType = 'application/json'
    }
    if ($PSCmdlet.ShouldProcess($ItemID,'DELETE'))
    {
        Invoke-MgGraphRequest @Account_params
    }

}
<#
.SYNOPSIS
Set basic fields for a user object or disable an account

.DESCRIPTION
Updated UPN, disable a user, Set firstname, lastname, or displayname

Permissions: https://learn.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&tabs=http

.PARAMETER UserPrincipalName
Parameter description

.PARAMETER NewUserPrincipalName
Parameter description

.PARAMETER accountEnabled
Parameter description

.PARAMETER FirstName
Parameter description

.PARAMETER LastName
Parameter description

.PARAMETER DisplayName
Parameter description

.EXAMPLE
Set-OGUser -UserPrincipalName jdoe@contoso.com -accountEnabled $false

.NOTES
General notes
#>

Function Set-OGUser {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory)]$UserPrincipalName,
        [Parameter(Mandatory = $false)][String]$NewUserPrincipalName,
        [Parameter(Mandatory = $false)][String]$accountEnabled,
        [Parameter(Mandatory = $false)][String]$FirstName,
        [Parameter(Mandatory = $false)][String]$LastName,
        [Parameter(Mandatory = $false)][String]$DisplayName
    )
    $User = Get-OGUser -UserPrincipalName $UserPrincipalName
    $bodyparams = @{}
    switch ($PSBoundParameters.Keys) {
        'NewUserPrincipalName' {
            $bodyparams.add('userPrincipalName', $NewUserPrincipalName)
        }
        'accountEnabled' {
            $bodyparams.add('accountEnabled', $accountEnabled)
        }
        'FirstName' {
            $bodyparams.add('givenName', $FirstName)
        }
        'LastName' {
            $bodyparams.add('surname', $LastName)
        }
        'DisplayName' {
            $bodyparams.add('displayName', $DisplayName)
        }
    }
    $Body = [PSCustomObject]@{}
    $body | Add-Member $bodyparams
    $account_params = @{
        Uri         = "/$GraphVersion/users/$($User.Id)"
        body        = $body | ConvertTo-Json -Depth 5
        Method      = 'PATCH'
        ContentType = 'application/json'
    }
    if ($PSCmdlet.ShouldProcess($UserPrincipalName, "set $($bodyparams.keys)")) {
        Invoke-MgGraphRequest @Account_params | Out-Null
    }
}
<#
.SYNOPSIS
Switch between graph api versions beta and v1.0

.DESCRIPTION
Switch between graph api versions beta and v1.0

.PARAMETER Beta
Parameter description

.PARAMETER v1
Parameter description

.EXAMPLE
Set-OGGraphVersion -Beta

.NOTES
General notes
#>

Function Set-OGGraphVersion {

    [CmdletBinding(DefaultParameterSetName = 'v1', SupportsShouldProcess)]
    param (
        [Parameter(Mandatory = $false,
            ParameterSetName = 'Beta')][switch]$Beta,
        [Parameter(Mandatory = $false,
            ParameterSetName = 'v1')][switch]$v1
    )
    if ($PSCmdlet.ShouldProcess("Graph Version", "set Graph API version to $($PSCmdlet.ParameterSetName)")) {
        switch ($PSCmdlet.ParameterSetName) {
            'Beta' {
                $Script:GraphVersion = 'beta'
            }
            'v1' {
                $Script:GraphVersion = 'v1.0'
            }
        }
    }
}


<#
.SYNOPSIS
Update an item in a SharePoint Online list

.DESCRIPTION
Update a SharePoint Online list item by providing the SharePoint site ID, the List ID, and the ID of the item to be updated. Next, provide the fields to be updated in a hash table

Permissions: https://learn.microsoft.com/en-us/graph/api/listitem-update?view=graph-rest-1.0&tabs=http

.EXAMPLE
$fields = @{
    field_1 = "Sample String"
}
Update-OGSiteListItem -SiteId 26776db6-ffd1-4e58-a6bf-851d6302733a -ListId 26f11389-ffd1-4e24-a7h1-85af93422733a -ItemId 1234 -Fields $fields

#>

function Update-OGSiteListItem {
    [CmdletBinding(SupportsShouldProcess)]
    Param(
        #SharePoint Site Identifier
        [Parameter(Mandatory)]
        [String]$SiteId
        ,
        #SharePoint List Identifier
        [Parameter(Mandatory)]
        [String]$ListId
        ,
        #SharePoint List Item Identifier
        [Parameter(Mandatory)]
        $ItemId
        ,
        #Hashtable of item fields and values to update in the item
        [Parameter(Mandatory)]
        [hashtable]$Fields


    )
    $URI = "/$GraphVersion/sites/$SiteId/lists/$ListId/items/$ItemId/fields"
    $account_params = @{
        URI         = $URI
        body        = $Fields | ConvertTo-Json -Depth 5
        Method      = 'PATCH'
        ContentType = 'application/json'
    }

    if ($PSCmdlet.ShouldProcess($ItemID,'PATCH'))
    {
        Invoke-MgGraphRequest @Account_params
    }
}
###############################################################################################
# Import User's Configuration
###############################################################################################
#Import-OGConfiguration
###############################################################################################
# Setup Tab Completion
###############################################################################################
# Tab Completions for IM Definition Names
<# $ImDefinitionsScriptBlock = {
  param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
  $MyParams = @{ }
  if ($null -ne $fakeBoundParameter.InstallManager)
  {
    $MyParams.InstallManager = $fakeBoundParameter.InstallManager
  }
  if ($null -ne $wordToComplete)
  {
    $MyParams.Name = $wordToComplete + '*'
  }
  $MyNames = Get-IMDefinition @MyParams |
    Select-Object -expandProperty Name

  foreach ($n in $MyNames)
  {
    [System.Management.Automation.CompletionResult]::new($n, $n, 'ParameterValue', $n)
  }
}

Register-ArgumentCompleter -CommandName @(
  'Get-IMDefinition'
  'Set-IMDefinition'
  'Remove-IMDefinition'
  'Update-IMInstall'
) -ParameterName 'Name' -ScriptBlock $ImDefinitionsScriptBlock #>