-
Notifications
You must be signed in to change notification settings - Fork 1
/
disable.ps1
422 lines (350 loc) · 18.1 KB
/
disable.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
#################################################
# HelloID-Conn-Prov-Target-Microsoft-Entra-ID-Disable
# Update account
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
# Set debug logging
switch ($actionContext.Configuration.isDebug) {
$true { $VerbosePreference = "Continue" }
$false { $VerbosePreference = "SilentlyContinue" }
}
$InformationPreference = "Continue"
$WarningPreference = "Continue"
#region functions
function Resolve-MicrosoftGraphAPIError {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[object] $ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
ScriptLineNumber = $ErrorObject.InvocationInfo.ScriptLineNumber
Line = $ErrorObject.InvocationInfo.Line
ErrorDetails = $ErrorObject.Exception.Message
FriendlyMessage = $ErrorObject.Exception.Message
}
if (-not [string]::IsNullOrEmpty($ErrorObject.ErrorDetails.Message)) {
$httpErrorObj.ErrorDetails = $ErrorObject.ErrorDetails.Message
}
elseif ($ErrorObject.Exception -is [System.Net.WebException] -and $ErrorObject.Exception.Response) {
$streamReaderResponse = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
if (-not [string]::IsNullOrEmpty($streamReaderResponse)) {
$httpErrorObj.ErrorDetails = $streamReaderResponse
}
}
try {
$errorObjectConverted = $httpErrorObj.ErrorDetails | ConvertFrom-Json -ErrorAction Stop
if ($errorObjectConverted.error_description) {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.error_description
}
elseif ($errorObjectConverted.error) {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.error.message
if ($errorObjectConverted.error.code) {
$httpErrorObj.FriendlyMessage += " Error code: $($errorObjectConverted.error.code)."
}
if ($errorObjectConverted.error.details) {
if ($errorObjectConverted.error.details.message) {
$httpErrorObj.FriendlyMessage += " Details message: $($errorObjectConverted.error.details.message)"
}
if ($errorObjectConverted.error.details.code) {
$httpErrorObj.FriendlyMessage += " Details code: $($errorObjectConverted.error.details.code)."
}
}
}
else {
$httpErrorObj.FriendlyMessage = $ErrorObject
}
}
catch {
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails
}
Write-Output $httpErrorObj
}
}
function Convert-StringToBoolean($obj) {
foreach ($property in $obj.PSObject.Properties) {
$value = $property.Value
if ($value -is [string]) {
try {
$obj.$($property.Name) = [System.Convert]::ToBoolean($value)
}
catch {
# Handle cases where conversion fails
$obj.$($property.Name) = $value
}
}
}
return $obj
}
function ConvertTo-FlatObject {
param (
[Parameter(Mandatory = $true)]
[pscustomobject] $Object,
[string] $Prefix = ""
)
$result = [ordered]@{}
foreach ($property in $Object.PSObject.Properties) {
$name = if ($Prefix) { "$Prefix`.$($property.Name)" } else { $property.Name }
if ($property.Value -is [pscustomobject]) {
$flattenedSubObject = ConvertTo-FlatObject -Object $property.Value -Prefix $name
foreach ($subProperty in $flattenedSubObject.PSObject.Properties) {
$result[$subProperty.Name] = [string]$subProperty.Value
}
}
else {
$result[$name] = [string]$property.Value
}
}
Write-Output ([PSCustomObject]$result)
}
#endregion functions
try {
#region account
# Define account object
$account = [PSCustomObject]$actionContext.Data.PsObject.Copy()
# Define properties to query
$accountPropertiesToQuery = @("id") + $account.PsObject.Properties.Name | Select-Object -Unique
# Remove properties of account object with null-values
$account.PsObject.Properties | ForEach-Object {
# Remove properties with null-values
if ($_.Value -eq $null) {
$account.PsObject.Properties.Remove("$($_.Name)")
}
}
# Convert the properties of account object containing "TRUE" or "FALSE" to boolean
$account = Convert-StringToBoolean $account
# Define properties to compare for update
$accountPropertiesToCompare = ConvertTo-FlatObject -Object $account | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
#endRegion account
#region Verify account reference
$actionMessage = "verifying account reference"
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw "The account reference could not be found"
}
#endregion Verify account reference
#region Create access token
$actionMessage = "creating access token"
$createAccessTokenBody = @{
grant_type = "client_credentials"
client_id = $actionContext.Configuration.AppId
client_secret = $actionContext.Configuration.AppSecret
resource = "https://graph.microsoft.com"
}
$createAccessTokenSplatParams = @{
Uri = "https://login.microsoftonline.com/$($actionContext.Configuration.TenantID)/oauth2/token"
Headers = $headers
Body = $createAccessTokenBody
Method = "POST"
ContentType = "application/x-www-form-urlencoded"
Verbose = $false
ErrorAction = "Stop"
}
$createAccessTokenResonse = Invoke-RestMethod @createAccessTokenSplatParams
Write-Verbose "Created access token. Expires in: $($createAccessTokenResonse.expires_in | ConvertTo-Json)"
#endregion Create access token
#region Create headers
$actionMessage = "creating headers"
$headers = @{
"Accept" = "application/json"
"Content-Type" = "application/json;charset=utf-8"
"Mwp-Api-Version" = "1.0"
}
Write-Verbose "Created headers. Result (without Authorization): $($headers | ConvertTo-Json)."
# Add Authorization after printing splat
$headers['Authorization'] = "Bearer $($createAccessTokenResonse.access_token)"
#endregion Create headers
#region Get account
# API docs: https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
$actionMessage = "querying account with ID: $($actionContext.References.Account)"
$getEntraIDAccountSplatParams = @{
Uri = "https://graph.microsoft.com/v1.0/users/$($actionContext.References.Account)?`$select=$($accountPropertiesToQuery -join ',')"
Method = "GET"
Verbose = $false
ErrorAction = "Stop"
}
Write-Verbose "SplatParams: $($getEntraIDAccountSplatParams | ConvertTo-Json)"
# Add header after printing splat
$getEntraIDAccountSplatParams['Headers'] = $headers
$getEntraIDAccountResponse = $null
$getEntraIDAccountResponse = Invoke-RestMethod @getEntraIDAccountSplatParams
$correlatedAccount = $getEntraIDAccountResponse
Write-Verbose "Queried account with ID: $($actionContext.References.Account). Result: $($correlatedAccount | ConvertTo-Json)"
#endregion Get account
#region Calulate action
$actionMessage = "calculating action"
if (($correlatedAccount | Measure-Object).count -eq 1) {
$actionMessage = "comparing current account to mapped properties"
# Set Previous data (if there are no changes between PreviousData and Data, HelloID will log "update finished with no changes")
$outputContext.PreviousData = $correlatedAccount.PsObject.Copy()
# Create flat reference object from correlated account
$accountReferenceObject = ConvertTo-FlatObject -Object $correlatedAccount
# Create flat difference object from mapped properties
$accountDifferenceObject = ConvertTo-FlatObject -Object $account
$accountSplatCompareProperties = @{
ReferenceObject = $accountReferenceObject.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
DifferenceObject = $accountDifferenceObject.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
}
if ($null -ne $accountSplatCompareProperties.ReferenceObject -and $null -ne $accountSplatCompareProperties.DifferenceObject) {
$accountPropertiesChanged = Compare-Object @accountSplatCompareProperties -PassThru
$accountOldProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "<=" }
$accountNewProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "=>" }
}
if ($accountNewProperties) {
# Create custom object with old and new values
$accountChangedPropertiesObject = [PSCustomObject]@{
OldValues = @{}
NewValues = @{}
}
# Add the old properties to the custom object with old and new values
foreach ($accountOldProperty in $accountOldProperties) {
$accountChangedPropertiesObject.OldValues.$($accountOldProperty.Name) = $accountOldProperty.Value
}
# Add the new properties to the custom object with old and new values
foreach ($accountNewProperty in $accountNewProperties) {
$accountChangedPropertiesObject.NewValues.$($accountNewProperty.Name) = $accountNewProperty.Value
}
Write-Verbose "Changed properties: $($accountChangedPropertiesObject | ConvertTo-Json)"
$actionAccount = "Update"
}
else {
$actionAccount = "NoChanges"
}
Write-Verbose "Compared current account to mapped properties. Result: $actionAccount"
}
elseif (($correlatedAccount | Measure-Object).count -eq 0) {
$actionAccount = "NotFound"
}
elseif (($correlatedAccount | Measure-Object).count -gt 1) {
$actionAccount = "MultipleFound"
}
#endregion Calulate action
#region Process
switch ($actionAccount) {
"Update" {
#region Update account
# API docs: https://learn.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&tabs=http
$actionMessage = "updating account with AccountReference: $($actionContext.References.Account | ConvertTo-Json)"
# Set $outputContext.Data with correlated account
$outputContext.Data = $correlatedAccount.PsObject.Copy()
# Create custom account object for update and set with updated properties
$updateAccountBody = [PSCustomObject]@{}
foreach ($accountProperty in $account.PsObject.Properties) {
$flatAccountProperty = ConvertTo-FlatObject -Object ($account | Select-Object $accountProperty.Name)
foreach ($flatAccountPropertyName in ($flatAccountProperty | Get-Member -MemberType 'NoteProperty').Name) {
if ($flatAccountPropertyName -in $accountNewProperties.Name) {
if ($flatAccountPropertyName -like "*.*") {
$parentPropertyName = ($flatAccountPropertyName -Split '\.')[0]
$subPropertyName = ($flatAccountPropertyName -Split '\.')[1]
$subPropertyValue = ($accountProperty.Value)."$subPropertyName"
if (-not ($parentPropertyName -in $updateAccountBody.PSObject.Properties.Name)) {
$updateAccountBody | Add-Member -MemberType NoteProperty -Name $parentPropertyName -Value ([PSCustomObject]@{}) -Force
# Update $outputContext.Data with updated field
$outputContext.Data | Add-Member -MemberType NoteProperty -Name $parentPropertyName -Value ([PSCustomObject]@{}) -Force
}
$updateAccountBody.$parentPropertyName | Add-Member -MemberType NoteProperty -Name $subPropertyName -Value $subPropertyValue -Force
# Update $outputContext.Data with updated field
$outputContext.Data.$parentPropertyName | Add-Member -MemberType NoteProperty -Name $subPropertyName -Value $subPropertyValue -Force
}
else {
$updateAccountBody | Add-Member -MemberType NoteProperty -Name $accountProperty.Name -Value $accountProperty.Value -Force
# Update $outputContext.Data with updated field
$outputContext.Data | Add-Member -MemberType NoteProperty -Name $accountProperty.Name -Value $accountProperty.Value -Force
}
}
}
}
# Convert the properties of custom account object for update containing "TRUE" or "FALSE" to boolean
$updateAccountBody = Convert-StringToBoolean $updateAccountBody
$updateAccountSplatParams = @{
Uri = "https://graph.microsoft.com/v1.0/users/$($actionContext.References.Account)"
Method = "PATCH"
Body = ($updateAccountBody | ConvertTo-Json -Depth 10)
ContentType = 'application/json; charset=utf-8'
Verbose = $false
ErrorAction = "Stop"
}
Write-Verbose "SplatParams: $($updateAccountSplatParams | ConvertTo-Json)"
if (-Not($actionContext.DryRun -eq $true)) {
# Add header after printing splat
$updateAccountSplatParams['Headers'] = $headers
$updateAccountResponse = Invoke-RestMethod @updateAccountSplatParams
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Updated account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Old values: $($accountChangedPropertiesObject.oldValues | ConvertTo-Json). New values: $($accountChangedPropertiesObject.newValues | ConvertTo-Json)."
IsError = $false
})
}
else {
Write-Warning "DryRun: Would update account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Old values: $($accountChangedPropertiesObject.oldValues | ConvertTo-Json). New values: $($accountChangedPropertiesObject.newValues | ConvertTo-Json)."
}
#endregion Update account
break
}
"NoChanges" {
#region No changes
$actionMessage = "skipping updating account"
$outputContext.Data = $correlatedAccount.PsObject.Copy()
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Skipped updating account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Reason: No changes."
IsError = $false
})
#endregion No changes
break
}
"NotFound" {
#region No account found
$actionMessage = "updating account"
# Throw terminal error
throw "No account found with ID: $($actionContext.References.Account)."
#endregion No account found
break
}
"MultipleFound" {
#region Multiple accounts found
$actionMessage = "updating account"
# Throw terminal error
throw "Multiple accounts found with ID: $($actionContext.References.Account). Please correct this to ensure the correlation results in a single unique account."
#endregion Multiple accounts found
break
}
}
#endregion Process
}
catch {
$ex = $PSItem
if ($($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or
$($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObj = Resolve-MicrosoftGraphAPIError -ErrorObject $ex
$auditMessage = "Error $($actionMessage). Error: $($errorObj.FriendlyMessage)"
$warningMessage = "Error at Line [$($errorObj.ScriptLineNumber)]: $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
}
else {
$auditMessage = "Error $($actionMessage). Error: $($ex.Exception.Message)"
$warningMessage = "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
}
if ($auditMessage -like "*ResourceNotFound*" -and $auditMessage -like "*Resource '$($actionContext.References.Account)' does not exist or one of its queried reference-property objects are not present*") {
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Skipped updating account with ID: $($actionContext.References.Account). Reason: No account found with ID: $($actionContext.References.Account). Possibly indicating that it could be deleted, or not correlated."
IsError = $false
})
}
else {
Write-Warning $warningMessage
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = $auditMessage
IsError = $true
})
}
}
finally {
# Check if auditLogs contains errors, if no errors are found, set success to true
if (-NOT($outputContext.AuditLogs.IsError -contains $true)) {
$outputContext.Success = $true
}
}