-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test_file2_adjust_group_label.ps1
390 lines (278 loc) · 11.5 KB
/
Test_file2_adjust_group_label.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
#https://github.com/microsoftgraph/powershell-aad-samples/blob/master/ReassignSensitivityLabelToO365Groups.ps1
#not working at present]
<#
.COPYRIGHT
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
See LICENSE in the project root for license information.
#>
function Get-AuthToken
{
<#
.SYNOPSIS
This function is used to authenticate with the MS Graph.
#>
param
(
[string]
[Parameter(Mandatory=$true)]
$TenantId
)
Write-Host "Checking for AzureAD module..."
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null)
{
Write-Host "`r`n"
Write-Host "AzureAD Powershell module is not installed." -f Red
Write-Host "`r`n"
Write-Host "Install by running 'Install-Module AzureAD' from an elevated PowerShell prompt." -f Yellow
exit
}
#
# If the AzureAD PowerShell module count is greater than 1, then find the latest version.
#
if($AadModule.count -gt 1)
{
$Latest_Version = ($AadModule | select version | Sort-Object)[-1]
$AadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }
#
# Checking if there are multiple modules of the latest version.
#
if($AadModule.count -gt 1)
{
$AadModule = $AadModule | select -Unique
}
}
#
# Getting path to Active Directory assemblies.
#
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
#
# Load Active Directory assemblies.
#
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
#
# Well-Known client ID for PowerShell.
#
$clientId = "1b730954-1685-4b74-9bfd-dac224a7b894"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$TenantId"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Always"
$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI, $clientId, $redirectUri, $platformParameters).Result
#
# If the access token is valid, then create the authorization header.
#
if($authResult.AccessToken -ne $null)
{
$authHeader = @{
'Content-Type'='application/json'
'Authorization'="Bearer " + $authResult.AccessToken
'ExpiresOn'=$authResult.ExpiresOn
}
return $authHeader
}
else
{
Write-Host "`r`n"
Write-Host "Authorization access token is null." -f Red
exit
}
}
function ReassignSensitivityLabelToO365Groups
{
<#
.SYNOPSIS
This function is used to reassign the given label to associated O365 groups in order to resolve conflicts due to label policy updates.
#>
param
(
[string]
[Parameter(Mandatory=$true)]
$LabelId,
[hashtable]
[Parameter(Mandatory=$true)]
$AuthHeader,
[string]
[Parameter(Mandatory=$true)]
$LogFile
)
$retryInterval = 5
$hostname = "https://graph.microsoft.com/beta"
$queryPageSize = 20
$contentType = "application/json"
$groupsQueryUriBase = $hostname + "/groups?"
$groupsFilterByAssignedLabelQuery = "`$top=$($queryPageSize)&`$select=id,displayName&`$filter=assignedLabels/any(x:x/labelId+eq+'$($LabelId)')"
while ($true)
{
$groupsFilterQueryUri = $groupsQueryUriBase + $groupsFilterByAssignedLabelQuery
#
# If a graph call fails, then the same operation will be retried for 3 times.
#
$retries = 3
$retryCount = 0
do
{
try
{
#
# GET request to filter groups by assigned label.
#
$groupsFilterQueryResult = Invoke-RestMethod -Uri $groupsFilterQueryUri -Headers $AuthHeader -Method Get
break
}
catch
{
if ($retries-- -gt 0)
{
$retryCount++
Write-Warning "Filter query to get groups by assigned label has failed and will be retried within $($retryInterval) seconds. Retry attempt: $($retryCount)"
Write-Host "`r`n"
Start-Sleep -Seconds $retryInterval
}
else
{
Write-Host $_.Exception.Message -f Red
if ($_.Exception.Response -ne $null)
{
$responseStream = $_.Exception.Response.GetResponseStream()
$streamReader = New-Object System.IO.StreamReader($responseStream)
$responseBody = $streamReader.ReadToEnd()
if (![string]::IsNullOrEmpty($responseBody))
{
$responseObject = $responseBody | ConvertFrom-Json
if ($responseObject -ne $null -and $responseObject.'error' -ne $null)
{
Write-Host "Error Code: " $responseObject.'error'.code -f Red
Write-Host "Error Message: " $responseObject.'error'.message -f Red
}
}
}
Write-Host "`r`n"
throw
}
}
}
while ($true)
$groups = $groupsFilterQueryResult.value
foreach ($group in $groups)
{
$groupUri = $hostname + "/groups/" + $group.id
$requestBody = @{
assignedLabels = @(
@{
labelId = $($LabelId)
}
)
}
$requestBody = $requestBody | ConvertTo-Json
$retries = 3
$retryCount = 0
do{
try
{
#
# PATCH request to reassign the given label to one of the associated groups.
#
Invoke-RestMethod -Uri $groupUri -Headers $AuthHeader -Method Patch -Body $requestBody -ContentType $contentType
Write-Host "The label has been reassigned to the following group object sucessfully:" -f Green
Write-Host "Group Object Id: " $group.id -f Green
Write-Host "Group Display Name: " $group.displayName -f Green
Write-Host "`r`n"
break
}
catch
{
if ($retries-- -gt 0)
{
$retryCount++
Write-Warning "Reassignment of the label has failed and will be retried for the following group object within $($retryInterval) seconds. Retry attempt: $($retryCount)"
Write-Host "Group Object Id: " $group.id -f Yellow
Write-Host "Group Display Name: " $group.displayName -f Yellow
Write-Host "`r`n"
Start-Sleep -Seconds $retryInterval
}
else
{
Write-Host "Reassignment of the label has failed on all attempts for the following group object:" -f Red
Write-Host "Group Object Id: " $group.id -f Red
Write-Host "Group Display Name: " $group.displayName -f Red
Write-Host "`r`n"
Write-Host $_.Exception.Message -f Red
#
# Write the group information and the exception message into a file.
#
Add-Content $LogFile -Value "Reassignment of the label has failed on all attempts for the following group object:"
Add-Content $LogFile -Value "Group Object Id: $($group.id)"
Add-Content $LogFile -Value "Group Display Name: $($group.displayName)"
Add-Content $LogFile -Value "`n"
Add-Content $LogFile -Value $_.Exception.Message
if ($_.Exception.Response -ne $null)
{
$responseStream = $_.Exception.Response.GetResponseStream()
$streamReader = New-Object System.IO.StreamReader($responseStream)
$responseBody = $streamReader.ReadToEnd()
if ($responseBody -ne $null)
{
$responseObject = $responseBody | ConvertFrom-Json
if ($responseObject -ne $null -and $responseObject.'error' -ne $null)
{
$errorCode = "Error Code: " + $responseObject.'error'.code
$errorMessage = "Error Message: " + $responseObject.'error'.message
Write-Host $errorCode -f Red
Write-Host $errorMessage -f Red
Add-Content $LogFile -Value $errorCode
Add-Content $LogFile -Value $errorMessage
}
}
}
Add-Content $LogFile -Value "-------------------------------------------------------------------------------------"
Add-Content $LogFile -Value "`n`n"
Write-Host "`r`n"
break
}
}
}while ($true)
}
if ($groupsFilterQueryResult.'@odata.nextLink' -eq $null)
{
break
}
$nextPageIndex = $groupsFilterQueryResult.'@odata.nextLink'.IndexOf('$')
$groupsFilterByAssignedLabelQuery = $groupsFilterQueryResult.'@odata.nextLink'.Substring($nextPageIndex)
}
}
function Main
{
<#
.SYNOPSIS
This function is used to:
1- Get an access token for MS Graph.
2- Reassign the given label to associated O365 groups.
.PARAMETER TenantId
Specifies the identifier of the target tenant.
.PARAMETER LabelId
Specifies the identifier of a label in the Security and Compliance Center.
.PARAMETER LogFile
Specifies the path to a file that would be used to log errors during reassignment of labels to groups.
.EXAMPLE
PS> Main -TenantId "00000000-0000-0000-0000-000000000000" -LabelId "00000000-0000-0000-0000-000000000000" -LogFile "C:\errors.txt"
#>
param
(
[string]
[Parameter(Mandatory=$true)]
$TenantId,
[string]
[Parameter(Mandatory=$true)]
$LabelId,
[string]
[Parameter(Mandatory=$true)]
$LogFile
)
$authHeader = Get-AuthToken -TenantId $TenantId
ReassignSensitivityLabelToO365Groups -LabelId $LabelId -AuthHeader $authHeader -LogFile $LogFile
}
Main