-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.ps1
364 lines (309 loc) · 14.3 KB
/
create.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
#################################################
# HelloID-Conn-Prov-Target-Microsoft-Exchange-Online-Create
# Correlate to account
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
# Define PowerShell commands to import
$commands = @(
"Get-User",
"Get-EXOMailbox",
"Set-Mailbox"
)
#region functions
function Resolve-ExchangeOnlineError {
[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.GetType().FullName -eq 'System.Net.WebException') {
if ($null -ne $ErrorObject.Exception.Response) {
$streamReaderResponse = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
if (-not [string]::IsNullOrEmpty($streamReaderResponse)) {
$httpErrorObj.ErrorDetails = $streamReaderResponse
}
}
}
try {
$errorObjectConverted = $ErrorObject | ConvertFrom-Json -ErrorAction Stop
if ($null -ne $errorObjectConverted.error_description) {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.error_description
}
elseif ($null -ne $errorObjectConverted.error) {
if ($null -ne $errorObjectConverted.error.message) {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.error.message
if ($null -ne $errorObjectConverted.error.code) {
$httpErrorObj.FriendlyMessage = $httpErrorObj.FriendlyMessage + " Error code: $($errorObjectConverted.error.code)"
}
}
else {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.error
}
}
else {
$httpErrorObj.FriendlyMessage = $ErrorObject
}
}
catch {
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails
}
Write-Output $httpErrorObj
}
}
function Convert-StringToBoolean($obj) {
if ($obj -is [PSCustomObject]) {
foreach ($property in $obj.PSObject.Properties) {
$value = $property.Value
if ($value -is [string]) {
$lowercaseValue = $value.ToLower()
if ($lowercaseValue -eq "true") {
$obj.$($property.Name) = $true
}
elseif ($lowercaseValue -eq "false") {
$obj.$($property.Name) = $false
}
}
elseif ($value -is [PSCustomObject] -or $value -is [System.Collections.IDictionary]) {
$obj.$($property.Name) = Convert-StringToBoolean $value
}
elseif ($value -is [System.Collections.IList]) {
for ($i = 0; $i -lt $value.Count; $i++) {
$value[$i] = Convert-StringToBoolean $value[$i]
}
$obj.$($property.Name) = $value
}
}
}
return $obj
}
#endregion functions
try {
#region account
# Define correlation
$correlationField = $actionContext.CorrelationConfiguration.accountField
$correlationValue = $actionContext.CorrelationConfiguration.personFieldValue
# Define account object
$account = [PSCustomObject]$actionContext.Data.PsObject.Copy()
# Define properties to query
$accountPropertiesToQuery = @("guid") + $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
#endRegion account
#region Verify correlation configuration and properties
$actionMessage = "verifying correlation configuration and properties"
if ($actionContext.CorrelationConfiguration.Enabled -eq $true) {
if ([string]::IsNullOrEmpty($correlationField)) {
throw "Correlation is enabled but not configured correctly."
}
if ([string]::IsNullOrEmpty($correlationValue)) {
throw "The correlation value for [$correlationField] is empty. This is likely a mapping issue."
}
}
else {
throw "Configuration of correlation is mandatory."
}
#endregion Verify correlation configuration and properties
#region Import module
$actionMessage = "importing module [ExchangeOnlineManagement]"
$importModuleSplatParams = @{
Name = "ExchangeOnlineManagement"
Cmdlet = $commands
Verbose = $false
ErrorAction = "Stop"
}
$null = Import-Module @importModuleSplatParams
Write-Information "Imported module [$($importModuleSplatParams.Name)]"
#endregion Create access token
#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://outlook.office365.com"
}
$createAccessTokenSplatParams = @{
Uri = "https://login.microsoftonline.com/$($actionContext.Configuration.TenantID)/oauth2/token"
Headers = $headers
Method = "POST"
ContentType = "application/x-www-form-urlencoded"
UseBasicParsing = $true
Body = $createAccessTokenBody
Verbose = $false
ErrorAction = "Stop"
}
$createAccessTokenResonse = Invoke-RestMethod @createAccessTokenSplatParams
Write-Information "Created access token."
#endregion Create access token
#region Connect to Microsoft Exchange Online
# Docs: https://learn.microsoft.com/en-us/powershell/module/exchange/connect-exchangeonline?view=exchange-ps
$actionMessage = "connecting to Microsoft Exchange Online"
$createExchangeSessionSplatParams = @{
Organization = $actionContext.Configuration.Organization
AppID = $actionContext.Configuration.AppId
AccessToken = $createAccessTokenResonse.access_token
CommandName = $commands
ShowBanner = $false
ShowProgress = $false
TrackPerformance = $false
SkipLoadingCmdletHelp = $true
SkipLoadingFormatData = $true
ErrorAction = "Stop"
}
$null = Connect-ExchangeOnline @createExchangeSessionSplatParams
Write-Information "Connected to Microsoft Exchange Online"
#endregion Connect to Microsoft Exchange Online
#region Get account
# Docs: https://learn.microsoft.com/en-us/powershell/module/exchange/get-exomailbox?view=exchange-ps
$actionMessage = "querying account where [$($correlationField)] = [$($correlationValue)]"
$getMicrosoftExchangeOnlineAccountSplatParams = @{
Filter = "$($correlationField) -eq '$($correlationValue)'"
Verbose = $false
ErrorAction = "Stop"
}
$getMicrosoftExchangeOnlineAccountResponse = $null
$getMicrosoftExchangeOnlineAccountResponse = Get-EXOMailbox @getMicrosoftExchangeOnlineAccountSplatParams
$correlatedAccount = $getMicrosoftExchangeOnlineAccountResponse | Select-Object $accountPropertiesToQuery
Write-Information "Queried account where [$($correlationField)] = [$($correlationValue)]. Result: $($correlatedAccount | ConvertTo-Json)"
#endregion Get account
#region Calulate action
$actionMessage = "calculating action"
if (($correlatedAccount | Measure-Object).count -eq 1) {
if ($account.PSObject.Properties.Name -Contains 'HiddenFromAddressListsEnabled') {
if ($correlatedAccount.HiddenFromAddressListsEnabled -ne $account.HiddenFromAddressListsEnabled) {
$actionAccount = "Update"
}
else {
$actionAccount = "Correlate"
}
}
else {
$actionAccount = "Correlate"
}
}
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" {
$actionMessage = "updating account"
$setMicrosoftExchangeOnlineAccountSplatParams = @{
Identity = $correlatedAccount.Guid
HiddenFromAddressListsEnabled = $account.HiddenFromAddressListsEnabled
Verbose = $false
ErrorAction = "Stop"
}
Write-Information "SplatParams: $($setMicrosoftExchangeOnlineAccountSplatParams | ConvertTo-Json)"
if (-Not($actionContext.DryRun -eq $true)) {
$null = Set-Mailbox @setMicrosoftExchangeOnlineAccountSplatParams
Write-Information "Account with id [$($correlatedAccount.Guid)] successfully correlated and updated [HideFromAddressListsEnabled = $($account.HiddenFromAddressListsEnabled)]"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Account with id [$($correlatedAccount.Guid)] successfully correlated and updated [HideFromAddressListsEnabled = $($account.HiddenFromAddressListsEnabled)]"
IsError = $false
})
}
else {
Write-Warning "DryRun: Would correlate and set account with id [$($correlatedAccount.Guid)] to [HideFromAddressListsEnabled = $($account.HiddenFromAddressListsEnabled)]."
}
$outputContext.AccountReference = "$($correlatedAccount.Guid)"
$outputContext.Data = $correlatedAccount.PsObject.Copy()
$outputContext.AccountCorrelated = $true
break
}
"Correlate" {
#region Correlate account
$actionMessage = "correlating to account"
$outputContext.AccountReference = "$($correlatedAccount.Guid)"
$outputContext.Data = $correlatedAccount.PsObject.Copy()
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "CorrelateAccount" # Optionally specify a different action for this audit log
Message = "Correlated to account with AccountReference: $($outputContext.AccountReference | ConvertTo-Json) on [$($correlationField)] = [$($correlationValue)]."
IsError = $false
})
$outputContext.AccountCorrelated = $true
#endregion Correlate account
break
}
"MultipleFound" {
#region Multiple accounts found
$actionMessage = "correlating to account"
# Throw terminal error
throw "Multiple accounts found where [$($correlationField)] = [$($correlationValue)]. Please correct this so the persons are unique."
#endregion Multiple accounts found
break
}
"NotFound" {
#region No account found
$actionMessage = "correlating to account"
# Throw terminal error
throw "No account found where [$($correlationField)] = [$($correlationValue)] while this connector only supports correlation."
#endregion No account 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-ExchangeOnlineError -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)"
}
Write-Warning $warningMessage
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = $auditMessage
IsError = $true
})
}
finally {
#region Disconnect from Microsoft Exchange Online
# Docs: https://learn.microsoft.com/en-us/powershell/module/exchange/disconnect-exchangeonline?view=exchange-ps
$actionMessage = "disconnecting to Microsoft Exchange Online"
$deleteExchangeSessionSplatParams = @{
Confirm = $false
ErrorAction = "Stop"
}
$null = Disconnect-ExchangeOnline @deleteExchangeSessionSplatParams
Write-Information "Disconnected from Microsoft Exchange Online"
#endregion Disconnect from Microsoft Exchange Online
# Check if auditLogs contains errors, if no errors are found, set success to true
if (-NOT($outputContext.AuditLogs.IsError -contains $true)) {
$outputContext.Success = $true
}
# Check if accountreference is set, if not set, set this with default value as this must contain a value
if ([String]::IsNullOrEmpty($outputContext.AccountReference) -and $actionContext.DryRun -eq $true) {
$outputContext.AccountReference = "DryRun: Currently not available"
}
}