-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathUpdate-GraphUserSettings.ps1
463 lines (407 loc) · 15.1 KB
/
Update-GraphUserSettings.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
<#
Microsoft provides programming examples for illustration only, without warranty either expressed or
implied, including, but not limited to, the implied warranties of merchantability and/or fitness
for a particular purpose. We grant You a nonexclusive, royalty-free right to use and modify the
Sample Code and to reproduce and distribute the object code form of the Sample Code, provided that
You agree: (i) to not use Our name, logo, or trademarks to market Your software product in which the
Sample Code is embedded; (ii) to include a valid copyright notice on Your software product in which
the Sample Code is embedded; and (iii) to indemnify, hold harmless, and defend Us and Our suppliers
from and against any claims or lawsuits, including attorneys' fees, that arise or result from the
use or distribution of the Sample Code.
This sample assumes that you are familiar with the programming language being demonstrated and the
tools used to create and debug procedures. Microsoft support professionals can help explain the
functionality of a particular procedure, but they will not modify these examples to provide added
functionality or construct procedures to meet your specific needs. if you have limited programming
experience, you may want to contact a Microsoft Certified Partner or the Microsoft fee-based consulting
line at (800) 936-5200.
#>
<#
.SYNOPSIS
Script to report and update on the Delve ContributionToContentDiscoveryDisabled setting for all or a subset of users in your organization.
.DESCRIPTION
Script to report and update on the Delve ContributionToContentDiscoveryDisabled setting for all or a subset of users in your organization.
.PARAMETER ReportOnly
Generate a CSV report of the users that would be updated with the specified ContributionToContentDiscoveryDisabled parameter setting. No updates will be made when using this switch.
.PARAMETER ContributionToContentDiscoveryDisabled
When set to $true, the delegate access to the user's trending API is disabled.
When set to $true, documents in the user's Office Delve are disabled.
When set to $true, the relevancy of the content displayed in Office 365, for example in Suggested sites in SharePoint Home and the Discover view in OneDrive for Business is affected.
Users can control this setting in Office Delve.
.PARAMETER AllUsers
Target all users in the organization excluding guests.
.PARAMETER TargetUsersCsvPath
Provide a CSV file path containing the target users. The must have at least one column called userPrincipalName for the script to use it.
.PARAMETER TargetUsersAADGroupName
Provide an Azure AD group display name containing the target users. The group may be a security group, distribution group of Office 365 group.
The app registration must have Group.Read.All permission to use this parameter.
.PARAMETER TargetUserName
Provide one or more Azure AD User Principal Names as the target users.
.EXAMPLE
.\Update-GraphUserSettings.ps1 -ContributionToContentDiscoveryDisabled $true -ReportOnly -AllUsers
Generate a CSV report of all users which currently have the ContributionToContentDiscoveryDisabled set to FALSE.
.EXAMPLE
.\Update-GraphUserSettings.ps1 -ContributionToContentDiscoveryDisabled $true -AllUsers
Update all users to set ContributionToContentDiscoveryDisabled to TRUE.
.EXAMPLE
.\Update-GraphUserSettings.ps1 -ContributionToContentDiscoveryDisabled $true -TargetUsersCsvPath .\Update-GraphUserSettings-TargetUsers.csv
Update the users listed in the CSV file to set ContributionToContentDiscoveryDisabled to TRUE.
.EXAMPLE
.\Update-GraphUserSettings.ps1 -ContributionToContentDiscoveryDisabled $true -TargetUsersAADGroupName 'Germany Employees'
Update the users in the 'Germany Employees' distribution group to set ContributionToContentDiscoveryDisabled to TRUE.
.EXAMPLE
.\Update-GraphUserSettings.ps1 -ContributionToContentDiscoveryDisabled $false -TargetUserName 'paul.muster@domain.tld','sophy.sample@domain.tld'
Update the users listed to set ContributionToContentDiscoveryDisabled to FALSE.
#>
# Script Parameters
param
(
[Parameter(Mandatory=$false)][switch]$ReportOnly,
[Parameter(Mandatory=$true)][bool]$ContributionToContentDiscoveryDisabled,
[Parameter(Mandatory=$false,ParameterSetName='AllUsers')][switch]$AllUsers,
[Parameter(Mandatory=$false,ParameterSetName='UsersFromCsv')][string]$TargetUsersCsvPath,
[Parameter(Mandatory=$false,ParameterSetName='UsersFromGroup')][string]$TargetUsersAADGroupName,
[Parameter(Mandatory=$false,ParameterSetName='UserPrincipalName')][string[]]$TargetUserName
)
function Get-Token
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)][string]$TenantID,
[Parameter(Mandatory = $true)][System.Guid]$ClientID,
[Parameter(Mandatory = $true)][string]$ClientSecret,
[Parameter(Mandatory = $true)][string]$Resource
)
begin
{
}
process {
$Body = @{
grant_type = 'client_credentials'
scope = "$Resource/.default"
client_id = $ClientID
client_secret = $ClientSecret
}
$RequestToken = @{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
Body = $Body
Uri = "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token"
}
try {
$response = Invoke-RestMethod @RequestToken
}
catch {
Write-Error $_.Exception
}
}
end
{
$response
}
}
function Get-AuthenticationHeaders
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$AccessToken
)
begin
{
}
process
{
@{
'Content-Type' = 'application/json'
'Authorization' = "Bearer $($AccessToken)"
}
}
end
{
}
}
function Split-ArrayIntoChunks
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][object[]]$Array,
[Parameter(Mandatory=$true)][int]$ChunkSize
)
begin
{
$counter = [pscustomobject] @{ Value = 0 }
}
process
{
$Array | Group-Object -Property { [math]::Floor($counter.Value++ / $ChunkSize) }
}
end
{
}
}
function Get-AllUsers
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$AccessToken
)
begin
{
$users = @()
$headers = Get-AuthenticationHeaders -AccessToken $AccessToken
$uri = "https://graph.microsoft.com/v1.0/users?`$select=userPrincipalName&`$filter=userType eq 'Member'" #Exclude Guest Accounts
}
process
{
# get all the users
do
{
$json = Invoke-RestMethod -Uri $uri -Headers $headers -Method GET
$users += $json.value
$uri = $json.'@odata.nextLink'
}
while( $uri )
}
end
{
$users
}
}
function Get-AllUsersInGroup
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$AccessToken,
[Parameter(Mandatory=$true)][string]$GroupDisplayName
)
begin
{
$users = @()
$headers = Get-AuthenticationHeaders -AccessToken $AccessToken
$getGroupIdUri = "https://graph.microsoft.com/v1.0/groups?`$filter=displayName eq '$GroupDisplayName'&`$select=id"
$getGroupMembersUpnUri = "https://graph.microsoft.com/v1.0/groups/{0}/members?`$select=userPrincipalName,userType"
}
process
{
# get group id
$groupJson = Invoke-RestMethod -Uri $getGroupIdUri -Headers $headers -Method GET
# validate we have one matching group
$groupId = $null
if ($groupJson -and $groupJson.value -and $groupJson.value.Length -gt 0)
{
if ($groupJson.value.length -eq 1) {
$groupId = $groupJson.value[0].id
}
else {
Write-Error "Found more than one group with display name '$GroupDisplayName'"
}
}
else {
Write-Error "Insufficient permissions or no group exists with display name '$GroupDisplayName'"
}
# get all users in the group
if ($null -ne $groupId)
{
do
{
$getGroupMembersUpnUri = $getGroupMembersUpnUri -f $groupId
$groupUsersJson = Invoke-RestMethod -Uri $getGroupMembersUpnUri -Headers $headers -Method GET
$users += $groupUsersJson.value
$getGroupMembersUpnUri = $groupUsersJson.'@odata.nextLink'
}
while( $getGroupMembersUpnUri )
}
# remove users that are guests
$users = $users | Where-Object {$_.userType -eq 'Member'}
}
end
{
$users
}
}
function CreateBatch-UpdateUserSettings
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string[]]$UserPrincipalNames,
[Parameter(Mandatory=$true)][bool]$ContributionToContentDiscoveryDisabled
)
begin
{
}
process
{
@{
'requests' = @(foreach($userPrincipalName in $UserPrincipalNames) {
@{
'id' = $userPrincipalName
'url' = "/users/$userPrincipalName/settings"
'method' = 'PATCH'
'headers' = @{
'Content-Type' = 'application/json'
}
'body' = @{
'contributionToContentDiscoveryDisabled' = $ContributionToContentDiscoveryDisabled
}
}
})
} | ConvertTo-Json -Depth 3 -Compress
}
end
{
}
}
function CreateBatch-GetUserSettings
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string[]]$UserPrincipalNames
)
begin
{
}
process
{
@{
'requests' = @(foreach($userPrincipalName in $UserPrincipalNames) {
@{
'id' = $userPrincipalName
'url' = "/users/$userPrincipalName/settings"
'method' = 'GET'
'headers' = @{
'Content-Type' = 'application/json'
}
}
})
} | ConvertTo-Json -Depth 3 -Compress
}
end
{
}
}
function Process-GraphBatch
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$Payload,
[Parameter(Mandatory=$true)][string]$AccessToken
)
begin
{
$headers = Get-AuthenticationHeaders -AccessToken $AccessToken
$uri = "https://graph.microsoft.com/v1.0/`$batch"
}
process
{
try
{
$response = Invoke-RestMethod -Uri $uri -Headers $headers -Body $Payload -Method Post
foreach ($batchResponse in $response.responses)
{
if ($batchResponse.status -ge 400)
{
Write-Error "Error in batch request: $($batchResponse.id). Error: $(ConvertTo-Json $batchResponse.body.error -Depth 5)"
}
}
}
catch
{
Write-Error "Error sending batch request. Error: $($_.Exception)"
}
}
end
{
$response
}
}
# script requires User.ReadWrite.All
# script requires Group.Read.All if using the -TargetUsersAADGroupName parameter (optional)
$tenantID = 'xxxxxxxx-xxx-xxxxxxx-xxxxxxxxxxxx' # aka Directory (tenant) ID in Azure Portal > Azure Active Directory > App Registrations
$clientId = 'xxx-xxxxx-xxxx-xxxxxxxxxxx-xxxxxx' # aka 'Application ID' in Azure Portal > Azure Active Directory > App Registrations
$clientSecret = 'xxxxxx-xxxxxx-xxx-xxxxxxxx-xxxx' # aka 'Keys' in Azure Portal > Azure Active Directory > App Registrations
# Graph $batch limit is 20
# https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching
$batchSize = 20
$token = $null
$token = Get-Token -Tenant $tenantID -ClientID $clientId -ClientSecret $clientSecret -Resource 'https://graph.microsoft.com'
if( -not $token -or -not $token.access_token )
{
break
}
$targetUsers = @()
switch ($PSCmdlet.ParameterSetName)
{
'AllUsers' {
Write-Host 'Fetching All Users from Microsoft Graph...'
$targetUsers = Get-AllUsers -AccessToken $token.access_token | Select-Object -ExpandProperty userPrincipalName
break
}
'UsersFromCsv' {
Write-Host 'Fetching Target Users from Csv...'
if (Test-Path $TargetUsersCsvPath) {
$userCsvRows = ConvertFrom-Csv (Get-Content $TargetUsersCsvPath)
foreach ($user in $userCsvRows) {
$targetUsers += $user.userPrincipalName
}
}
break
}
'UsersFromGroup' {
Write-Host 'Fetching Target Users in AAD Group from Microsoft Graph...'
$targetUsers = Get-AllUsersInGroup -GroupDisplayName $TargetUsersAADGroupName -AccessToken $token.access_token | Select-Object -ExpandProperty userPrincipalName
break
}
'UserPrincipalName' {
Write-Host 'Using given Target Users...'
$targetUsers = $TargetUserName
break
}
}
if ( $targetUsers.Length -eq 0 )
{
break
}
Write-Host "Splitting $($targetUsers.Count) users into $([Math]::Ceiling($targetUsers.Count / $batchSize)) batches..."
$batches = Split-ArrayIntoChunks -Array $targetUsers -ChunkSize $batchSize
if ($ReportOnly)
{
# Remove existing CSV if there is one on -ReportOnly mode
Remove-Item -Path 'DelveUserSettingsReport.csv' -Force -ErrorAction SilentlyContinue
}
# Iterate each batch of users to create Graph $batch JSON payload
for ($idx = 0; $idx -lt $batches.Length; $idx++)
{
$batch = $batches[$idx].Group
if ($ReportOnly)
{
Write-Host "Processing Batch: $($idx + 1) of $($batches.Length) [Batch Size: $($batch.Count)]`t-ReportOnly"
$batchPayload = CreateBatch-GetUserSettings -UserPrincipalNames $batch
$result = Process-GraphBatch -Payload $batchPayload -AccessToken $token.access_token
foreach ($batchResponse in $result.responses)
{
$userPrincipalName = $batchResponse.id
$currentSetting = $batchResponse.body.contributionToContentDiscoveryDisabled
if ($null -eq $currentSetting)
{
$currentSetting = 'Check Account'
}
[PSCustomObject] @{
UserPrincipalName = $userPrincipalName
ContributionToContentDiscoveryDisabled = $currentSetting
} | Export-Csv -Path 'DelveUserSettingsReport.csv' -NoTypeInformation -Append
}
}
else
{
Write-Host "Processing Batch: $($idx + 1) of $($batches.Length) [Batch Size: $($batch.Count)]"
$batchPayload = CreateBatch-UpdateUserSettings -UserPrincipalNames $batch -ContributionToContentDiscoveryDisabled $ContributionToContentDiscoveryDisabled
Process-GraphBatch -Payload $batchPayload -AccessToken $token.access_token | Out-Null
}
}