-
Notifications
You must be signed in to change notification settings - Fork 12
/
Groups.ps1
2527 lines (2424 loc) · 132 KB
/
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
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(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,
#A field to sort by - sorting is applied on the client side because filter and selct cannot be combined with server-side sort
[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 = 'displayName',
[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 -and $name -match '\*.*\*|^\*.+') { # ie. *xxx* or xxx* but not "*" alone or xxx*
$uri = $GraphUri + '/Groups/?$search="displayname:' + ($Name -replace '\*','') +'"'
}
elseif ($Name -ne '*') {$uri = $GraphUri + '/Groups/?$filter=' +(FilterString $Name)}
elseif ($orderby) {$uri = $GraphUri + '/Groups/?$OrderBy=' + $OrderBy }
else {$uri = $GraphUri + '/Groups/' }
Write-Progress -Activity "Finding Groups"
Invoke-GraphRequest -Uri $uri -AllValues -ExcludeProperty 'creationOptions' -AsType ([MicrosoftGraphGroup]) -Headers @{'consistencyLevel'='eventual'} |
Where-Object {$_.displayname -like $Name -or $_.displayname -like [WildcardPattern]::Escape($Name)} |
Sort-Object -Property $OrderBy -Descending:$Descending
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 called 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",
giving the "Shared Documents" list for each team
.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 'childre'n property
which contains files and folder objects, and 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 be 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,
#Field(s) to select for the members or owners of the group : ID and displayname are always included
[Parameter(Mandatory=$false, parameterSetName='Members')]
[Parameter(Mandatory=$false, parameterSetName='TransitiveMembers')]
[parameter(Mandatory=$false, parameterSetName="Owners")]
[ValidateSet ('aboutMe', 'accountEnabled' , 'activities', 'ageGroup', 'agreementAcceptances' , 'appRoleAssignments',
'assignedLicenses', 'assignedPlans', 'authentication', 'birthday', 'businessPhones',
'calendar', 'calendarGroups', 'calendars', 'calendarView', 'city', 'companyName', 'consentProvidedForMinor',
'contactFolders', 'contacts', 'country', 'createdDateTime', 'createdObjects', 'creationType' ,
'deletedDateTime', 'department', 'directReports', 'displayName', 'drive', 'drives',
'employeeHireDate', 'employeeId', 'employeeOrgData', 'employeeType', 'events', 'extensions',
'externalUserState', 'externalUserStateChangeDateTime', 'faxNumber', 'followedSites', 'givenName', 'hireDate',
'id', 'identities', 'imAddresses', 'inferenceClassification', 'insights', 'interests', 'isResourceAccount', 'jobTitle', 'joinedTeams',
'lastPasswordChangeDateTime', 'legalAgeGroupClassification', 'licenseAssignmentStates', 'licenseDetails' ,
'mail' , 'mailFolders' , 'mailNickname', 'managedAppRegistrations', 'managedDevices', 'manager' , 'memberOf' , 'messages', 'mobilePhone', 'mySite',
'oauth2PermissionGrants' , 'officeLocation', 'onenote', 'onlineMeetings' , 'onPremisesDistinguishedName', 'onPremisesDomainName',
'onPremisesExtensionAttributes', 'onPremisesImmutableId', 'onPremisesLastSyncDateTime', 'onPremisesProvisioningErrors', 'onPremisesSamAccountName',
'onPremisesSecurityIdentifier', 'onPremisesSyncEnabled', 'onPremisesUserPrincipalName', 'otherMails', 'outlook', 'ownedDevices', 'ownedObjects',
'passwordPolicies', 'passwordProfile', 'pastProjects', 'people', 'photo', 'photos', 'planner', 'postalCode', 'preferredLanguage',
'preferredName', 'presence', 'provisionedPlans', 'proxyAddresses', 'registeredDevices', 'responsibilities',
'schools', 'scopedRoleMemberOf', 'settings', 'showInAddressList', 'signInSessionsValidFromDateTime', 'skills', 'state', 'streetAddress', 'surname',
'teamwork', 'todo', 'transitiveMemberOf', 'usageLocation', 'userPrincipalName', 'userType')]
[String[]]$UserProperties = $Script:DefaultUserProperties ,
#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 items can't be filtered by name ... perhaps notebooks can but a group only has one.
[Parameter(parameterSetName='Channels')]
[ArgumentCompleter([ChannelCompleter])]
[String]$ChannelName,
#Field(s) to select for the group: ID and displayname are always included
[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,
[switch]$Mine,
[Parameter(Mandatory=$true, parameterSetName='BareGroups')]
[switch]$NoTeamInfo
)
begin {
function sendUsersAndGroups {
param (
[parameter(valueFromPipeline=$true)]
$ug ,
$DisplayName
)
process {
if ($ug.'@odata.type' -match 'group$') {
$disallowedProperties = $ug.keys.where({$_ -notin $script:GroupProperties})
foreach ($p in $disallowedProperties) {$null = $ug.remove($p)}
New-Object -Property $ug -TypeName MicrosoftGraphGroup |
Add-Member -PassThru -NotePropertyName GroupName -NotePropertyValue $displayname
}
elseif ($ug.'@odata.type' -match 'user$') {
$disallowedProperties = $ug.keys.where({$_ -notin $script:UserProperties})
foreach ($p in $disallowedProperties) {$null = $ug.remove($p)}
New-Object -Property $ug -TypeName MicrosoftGraphUser |
Add-Member -PassThru -NotePropertyName GroupName -NotePropertyValue $displayname
}
}
}
}
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 - it may be a wildcard
# The proceed as if ID had been passed as one or more groups.
elseif ($ID -is [string] -and $ID -notmatch $guidregex) {
$ID = Get-GraphGroupList -Name $id
if (-not $id) {Write-Warning "'$($PSBoundParameters['id'])' did not match any groups."; return}
}
# We'll loop through an array (or single object) with either GUIDs or objects.
foreach ($i in $ID) {
<# not all teams have team set in resource provisioning 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.id -and -not $i.DisplayName) {
$i = Invoke-GraphRequest "$GraphUri/groups/$($i.id)"
}
elseif ($i -is [string] -and $i -match $guidregex) {
$i = Invoke-GraphRequest "$GraphUri/groups/$i" }
elseif ($i -is [string]) {
$i = Get-GraphGroupList -Name $i}
if (-not ($i.DisplayName -and $i.id)) {
Write-Warning 'Could not resoulve the group' ; continue
}
if ($Owners -or $Members -or $TransitiveMembers) {
if ('id' -notin $UserProperties) {$UserProperties += 'id'}
if ('displayName' -notin $UserProperties) {$UserProperties += 'displayName'}
$UserPropertiesSelect = '?$Select=' + ($UserProperties -join ',')
}
$displayname = $i.DisplayName
$groupid = $teamid = $i.id
$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 '[email protected]', '@odata.context', '[email protected]', '[email protected]' -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", "[email protected]" -AsType ([MicrosoftGraphDrive]) |
Add-Member -PassThru -NotePropertyName GroupName -NotePropertyValue $displayname
continue
}
elseif ($Owners) {
Invoke-GraphRequest -Uri "$groupURI/Owners$UserPropertiesSelect" -AllValues | sendUsersAndGroups -Displayname $displayname
continue
}
elseif ($Members) { #can do group ?$expand=Memebers, the others don't expand
Invoke-GraphRequest -Uri "$groupURI/members$UserPropertiesSelect" -AllValues | sendUsersAndGroups -Displayname $displayname
continue
}
elseif ($TransitiveMembers) {
Invoke-GraphRequest -Uri "$groupURI/TransitiveMembers?$UserPropertiesSelect" -AllValues | sendUsersAndGroups -Displayname $displayname
continue
}
#xxxx Allow group properties for memeber of ?
elseif ($MemberOf) {
Invoke-GraphRequest -Uri "$groupURI/memberof" -AllValues | sendUsersAndGroups -Displayname $displayname
continue
}
elseif ($TransitiveMemberOf) {
$usersAndGroups += Invoke-GraphRequest -Uri "$groupURI/TransitiveMemberof" -AllValues | sendUsersAndGroups -Displayname $displayname
continue
}
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 '[email protected]' -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]
}
continue
}
elseif ($Threads) {
Invoke-GraphRequest -Uri "$groupURI/threads" -AllValues -AsType ([MicrosoftGraphConversationThread]) |
Add-Member -PassThru -NotePropertyName Group -NotePropertyValue $groupid |
Add-Member -PassThru -NotePropertyName GroupName -NotePropertyValue $displayname
continue
}
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]) -ExcludeProperty "tenantId" |
Add-Member -PassThru -NotePropertyName Team -NotePropertyValue $teamid |
Add-Member -PassThru -NotePropertyName TeamName -NotePropertyValue $displayname
continue
}
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
continue
}
elseif ($Select) {
$SelectList = (@('id','displayName') + $Select ) -join','
Invoke-GraphRequest -Uri "$groupuri`?`$Select=$SelectList" -As ([MicrosoftGraphGroup]) -ExcludeProperty '@odata.context'
}
else {
$g = Invoke-GraphRequest -Uri $groupuri -As ([MicrosoftGraphGroup]) -ExcludeProperty '@odata.context','creationOptions'
#removed $expand=Members as it only returns the first 20.
if ($g.resourceProvisioningOptions -notcontains 'Team' -or
$MyInvocation.InvocationName -ne 'Get-GraphTeam' -or $NoTeamInfo) { $g }
else {
$t = Invoke-GraphRequest -Uri "$teamURI" -As ([MicrosoftGraphTeam]) -ExcludeProperty '@odata.context'
# $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 $_ }
}
}
}
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,
#Some settings can only be set when the group is created By default any user in the organization can post conversations to the group,
#groups are visible and discoverable in Outlook, New Group-Members are not subscribed to conversations and a welcome mail is sent.
[validateSet('AllowOnlyMembersToPost', 'HideGroupInOutlook', 'SubscribeNewGroupMembers', 'WelcomeEmailDisabled')]
[string[]]$BehaviorOptions,
#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 ($BehaviorOptions) {
$settings["resourceBehaviorOptions"] = $BehaviorOptions
}
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['[email protected]'] = @();
foreach ($m in $Members) {
if ($m.id) {$settings['[email protected]'] += "$GraphUri/users/$($m.id)"}
else {$settings['[email protected]'] += "$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['[email protected]'] = @()
foreach ($o in $Owners) {
if ($o.id) {$settings['[email protected]'] += "$GraphUri/users/$($o.id)"}
else{ $settings['[email protected]'] += "$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 ($Owners) { $
Write-Progress -Activity 'Creating Group/Team' -CurrentOperation "Setting Group ownership on $Name"
Owners | Add-GraphGroupMember -Group $group -AsOwner -Force
}
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 #Check that all users are returned if more than 20 added on creation.
$team.visibility = $group.visibility
Write-Progress -Activity 'Creating Group/Team' -Completed
$team
}
}
}
function idfromteam {
<#
.synopsis
Helper function to return a team ID - filters out not teams-enabled groups
.Description
if $team is null or emptry, returns nothing.
if it has an ID property returns the ID with no further checks
if it is a string holding a GUID, it it returns the string with no further checks
if it is any other string searches for any group with a matching display name and returns the result(s)
#>
param (
$Team
)
if (-not $Team) {return}
if ($Team.id) {return $Team.id}
if ($Team -is [string] -and
$Team -match $GUIDRegex) {return $Team}
elseif ($Team -is [string]) {
Invoke-GraphRequest ("$GraphUri/groups?`$select=id,resourceProvisioningOptions,displayname&`$filter=" + (FilterString $Team)) -ValueOnly |
ForEach-Object {if ("Team" -in $_.resourceProvisioningOptions) {$_.id}}
}
}
function idfromgroup {
<#
.synopsis
Helper function to return a Group ID - filters out not Groups-enabled groups
.Description
if $Group is null or emptry, returns nothing.
if it has an ID property returns the ID with no further checks
if it is a string holding a GUID, it it returns the string with no further checks
if it is any other string searches for any group with a matching display name and returns the result(s)
#>
param (
$Group
)
foreach ($g in $Group) {
if ($g.id) {$g.id}
if ($g -is [string] -and
$g -match $GUIDRegex) {$g}
elseif ($g -is [string]) {
Invoke-GraphRequest ("$GraphUri/groups?`$select=id,resourceProvisioningOptions,displayname&`$filter=" + (FilterString $g)) -ValueOnly |
ForEach-Object {$_.id}
}
}
}
function Set-GraphDefaultGroup {
<#
.Synopsis
Sets the default paramater for group or team in most functions which take one.
.Description
Takes a group as a parameter or via the pipeline.
If a string is passed it will try to get a matching group from Get-GraphGroup,
a string may be a wildcard for a group name - provided that it only finds one matching group.
If the group has been provisioned as a team then it will be the default for commands which take a -Team parameter.
The primary purpose is to avoid specifying a Group/Team when working with messages, calendar / planner / team channels,
but working with the group itself or its membership it is safer not to default the selection, so no defaults
are set for for Set-Team, Set-Group, Get- Remove-Group Remove-GroupMember or Add-GroupMember or Import and Export
.Example
> Set-GraphDefaultGroup Accounts
> Get-GraphChannel
Display Name description
----------- -----------
General The Accounts Department
Mccaw For anything about project Mccaw
The first command sets the default group - because "Accounts" has been provisioned as a team,
it becomes the default team for Get-GraphChannel
#>
[Alias('Set-GraphDefaultTeam')]
Param (
#The group to set as the default for other commands
[Alias('Team')]
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[AllowEmptyString()]
[AllowNull()]
[ArgumentCompleter([GroupCompleter])]
$Group
)
@('*-GraphChannel*:Team','Add-Graph*Tab:Team','*New-GraphTeamPlan:Team',
'*-GraphEvent:Group','*-GraphGroupThread:Group','Get-GraphGroupConversation:Group') | ForEach-Object {
$null = $Global:PSDefaultParameterValues.Remove($_)
}
if ($Group -is [string]) {$Group = Get-GraphGroup $Group -NoTeamInfo}
if (-not $Group -or ($group.Count -gt 1)){
Write-Warning 'Could not resolve the information provided to a single group.'
}
elseif ($Group.securityEnabled) {
Write-Warning "Only commands for unified groups accept a default, but $($Group.DisplayName) is a security group."
}
else {
$Global:PSDefaultParameterValues[ '*-GraphEvent:Group'] = $Group
$Global:PSDefaultParameterValues[ '*-GraphGroupThread:Group'] = $Group
$Global:PSDefaultParameterValues[ 'Send-GraphGroupReply:Group'] = $Group
$Global:PSDefaultParameterValues['Get-GraphGroupConversation:Group'] = $Group
if ($Group.ResourceProvisioningOptions -contains 'team' -or $Group -is [MicrosoftGraphTeam]){
$Global:PSDefaultParameterValues[ '*-GraphChannel*:Team'] = $Group
$Global:PSDefaultParameterValues[ 'Add-Graph*Tab:Team'] = $Group
$Global:PSDefaultParameterValues[ '*New-GraphTeamPlan:Team'] = $Group
}
}
}
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 -and $g.displayname) {$g}
else {Get-GraphGroup $g -NoTeamInfo -ErrorAction Stop }
}
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 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,ConfirmImpact='High')]
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
)
begin {
$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) {
$webparams = @{
'Method' = 'PATCH'
'ContentType' = 'application/json'
'Body' = ConvertTo-Json $settings -Depth 10
}
Write-Debug $webparams['Body']
}
else {Write-Warning -Message "Nothing to set"}
}
process {
if (-not $webparams) {return}
Write-Progress -Activity "Updating Team" -Status "Checking team is valid"
if ($Team.id -and $Team.DisplayName -and
($Team -is [MicrosoftGraphTeam] -or
$Team.resourceProvisioningOptions -contains 'Team')) {
$group = $team
}
elseif ($Team.id) {
$group = Invoke-GraphRequest -method get "$GraphUri/groups/$($Team.id)"
}
elseif ($Team -is [string] -and $team -match $GuidRegex ) {
$group = Invoke-GraphRequest -method get "$GraphUri/groups/$Team"
}
elseif ($Team -is [string] ) {
$group = Get-GraphGroupList -Name $Team
}
if ( $group.id -and $group.displayName -and
($group.resourceProvisioningOptions -contains 'Team' -or
$group -is [MicrosoftGraphTeam] )) {
$webparams['Uri'] = "$GraphUri/teams/$($group.id)"
}
else {
Write-Progress -Activity "Updating Team" -Completed
Write-Warning -Message 'Could not resolve the team';
return
}
if ($PSCmdlet.ShouldProcess($group.displayName,'Update Team settings')) {
Write-Progress -Activity "Updating Team" -CurrentOperation $group.displayName -Status "Committing changes"
Invoke-GraphRequest @webparams
Write-Progress -Activity "Updating Team" -Completed
}
}
}
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.
Deleted groups can be recovered using Get-GraphDeletedObject and Restore-GraphDeletedObject
#>
[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 -and $g.displayname) {$g}
else {Get-GraphGroup $g -NoTeamInfo -ErrorAction Stop }
}
foreach ($g in $Group){
if ($Force -or $PSCmdlet.Shouldprocess("$($g.displayname)","Delete Group")) {
Write-Progress -Activity "Deleting Group" -CurrentOperation $g.displayname
Invoke-GraphRequest -Method Delete -Uri "$GraphUri/groups/$($g.id)/"
Write-Verbose "REMOVED GROUP $($g.displayname)"
}
}
Write-Progress -Activity "Deleting Group" -Completed
}
}
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 [email protected] -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 -and $g.displayname) {$g}
else {Get-GraphGroup $g -NoTeamInfo -ErrorAction Stop }
}
}
$memberHash = @{}
foreach ($g in $Group) {
$memberHash[$g.id] = Get-GraphGroup -ID $g.id -Members | Select-Object -ExpandProperty id
}
}
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"}
#There is more efficient way to add many users, but that isn't the main use case so using one call per user.
#That optimization would be to collect piped user in the process block and make one call per group 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 -and $g.displayname)) {
try {$m = Get-GraphUser -User $m -Select displayname}
catch {throw "Could not get a user matching $m"; return }