-
Notifications
You must be signed in to change notification settings - Fork 2
/
persons.ps1
630 lines (519 loc) · 25.6 KB
/
persons.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
#####################################################
# HelloID-Conn-Prov-Source-ADP-Workforce
#
# Version: 2.2.0
#####################################################
# Set TLS to accept TLS, TLS 1.1 and TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
# Set debug logging
switch ($($c.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
$InformationPreference = "Continue"
$WarningPreference = "Continue"
$c = $configuration | ConvertFrom-Json
$baseUrl = $($c.BaseUrl)
$clientId = $($c.ClientID)
$clientSecret = $($c.ClientSecret)
$certificatePath = $($c.CertificatePath)
$certificateBase64 = $c.CertificateBase64
$certificatePassword = $($c.CertificatePassword)
$proxyServer = $($c.ProxyServer)
Write-Information "Start person import: Base URL '$baseUrl', Proxy server '$proxyServer', Client ID '$clientId'"
#region functions
function Resolve-HTTPError {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
FullyQualifiedErrorId = $ErrorObject.FullyQualifiedErrorId
MyCommand = $ErrorObject.InvocationInfo.MyCommand
RequestUri = $ErrorObject.TargetObject.RequestUri
ScriptStackTrace = $ErrorObject.ScriptStackTrace
ErrorMessage = ''
}
if ($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') {
$httpErrorObj.ErrorMessage = $ErrorObject.ErrorDetails.Message
}
elseif ($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException') {
$httpErrorObj.ErrorMessage = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
}
Write-Output $httpErrorObj
}
}
function Get-ErrorMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$errorMessage = [PSCustomObject]@{
VerboseErrorMessage = $null
AuditErrorMessage = $null
}
if ( $($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$httpErrorObject = Resolve-HTTPError -Error $ErrorObject
$errorMessage.VerboseErrorMessage = $httpErrorObject.ErrorMessage
$errorMessage.AuditErrorMessage = $httpErrorObject.ErrorMessage
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($errorMessage.VerboseErrorMessage)) {
$errorMessage.VerboseErrorMessage = $ErrorObject.Exception.Message
}
if ([String]::IsNullOrEmpty($errorMessage.AuditErrorMessage)) {
$errorMessage.AuditErrorMessage = $ErrorObject.Exception.Message
}
Write-Output $errorMessage
}
}
function Get-ADPAccessToken {
<#
.SYNOPSIS
Retrieves an AccessToken from the ADP API using the standard <Invoke-RestMethod> cmdlet
.DESCRIPTION
The ADP Workforce API's uses OAuth for authentication\authorization.
Before data can be retrieved from the API's, an AccessToken has to obtained. The AccessToken is used for all consecutive calls to the ADP Workforce API's.
Tokens only have access to a certain API scope. Default the scope is set to: 'worker-demographics organization-departments'.
Data outside this scope from other API's cannot be retrieved
.PARAMETER ClientID
The ClientID for the ADP Workforce environment. This will be provided by ADP
.PARAMETER ClientSecret
The ClientSecret for the ADP Workforce environment. This will be provided by ADP
.PARAMETER Certificate
The [X509Certificate] object containing the *.pfx
.EXAMPLE
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new("the path to the *.pfx file", "Password for the *.pfx certificate")
Get-ADPAccessToken -Client 'ADP_Provided_ClientID' -ClientSecret 'ADP_Provided_Secret' -Certifcate $certificate
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[String]
$ClientID,
[Parameter(Mandatory)]
[String]
$clientSecret,
[X509Certificate]
$Certificate
)
$headers = @{
"content-type" = "application/x-www-form-urlencoded"
}
$body = @{
client_id = $ClientID
client_secret = $clientSecret
grant_type = "client_credentials"
}
try {
$splatRestMethodParameters = @{
Uri = "$BaseUrl/auth/oauth/v2/token"
Method = 'POST'
Headers = $headers
Body = $body
Certificate = $certificate
}
Invoke-RestMethod @splatRestMethodParameters -verbose:$false
}
catch {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
function Invoke-ADPRestMethod {
<#
.SYNOPSIS
Retrieves data from the ADP API's
.DESCRIPTION
Retrieves data from the ADP API's using the standard <Invoke-RestMethod> cmdlet
.PARAMETER Url
The BaseUrl to the ADP Workforce environment. For example: https://test-api.adp.com
.PARAMETER Method
The CRUD operation for the request. Valid HttpMethods inlcude: GET and POST. Note that the ADP API's needed for the connector will only support 'GET'
.PARAMETER AccessToken
The AccessToken retrieved by the <Get-ADPAccessToken> function
.PARAMETER ProxyServer
The URL (or IP Address) to the ProxyServer in the network. Leave empty if no ProxyServer is being used
.PARAMETER Certificate
The [X509Certificate] object containing the *.pfx
.EXAMPLE
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new("the path to the *.pfx file", "Password for the *.pfx certificate")
Invoke-ADPRestMethod -Uri 'https://test-api.adp.com/hr/v2/worker-demographics' -Method 'GET' -AccessToken '0000-0000-0000-0000' -Certifcate $certificate
Returns the raw JSON data containing all workers from ADP Workforce
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[String]
$Url,
[Parameter(Mandatory)]
[String]
$Method,
[Parameter(Mandatory)]
[String]
$AccessToken,
[AllowNull()]
[AllowEmptyString()]
[String]
$ProxyServer,
[Parameter(Mandatory)]
[X509Certificate]
$Certificate,
[parameter(Mandatory = $true)]
[ref]
$data
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
}
if ([string]::IsNullOrEmpty($ProxyServer)) {
$proxy = $null
}
else {
$proxy = $ProxyServer
}
# Speficy the variables specific to certain endpoints
# $contentField = The field in the response content that contains the actual data
# $paging = A boolean specifying to user paging or not
switch ($Url) {
"https://api.eu.adp.com/hr/v2/worker-demographics" {
$contentField = "workers"
$paging = $true
}
"https://api.eu.adp.com/core/v1/organization-departments" {
$contentField = "organizationDepartments"
$paging = $false
}
}
try {
# Currently only supported for the worker-demographics endpoint
if ($true -eq $paging) {
# Fetch the data in smaller chunks, otherwise the API of ADP will return an error 500 Internal Server Error or an error 503 Server / Service unavailable
$take = 100
$skip = 0
do {
$result = $null
$urlOffset = $Url + "?$" + "skip=$skip&$" + "top=$take"
$skip += $take
$splatRestMethodParameters = @{
Uri = $urlOffset
Method = $Method
Headers = $headers
Proxy = $proxy
UseBasicParsing = $true
Certificate = $Certificate
}
$datasetJson = Invoke-WebRequest @splatRestMethodParameters -verbose:$false
if (-not[string]::IsNullOrEmpty($certificateBase64)) {
$dataset = $datasetJson.content | ConvertFrom-Json
}
elseif (-not [string]::IsNullOrEmpty($certificatePathertificatePath)) {
$datasetCorrected = [Text.Encoding]::UTF8.GetString([Text.Encoding]::UTF8.GetBytes($datasetJson.content))
$dataset = $datasetCorrected | ConvertFrom-Json
}
else {
Throw "No certificate configured"
}
$result = $dataset.$contentField
if (-not [string]::IsNullOrEmpty($result)) {
$data.value.AddRange($result)
}
}until( [string]::IsNullOrEmpty($result))
}
else {
$result = $null
$splatRestMethodParameters = @{
Uri = $Url
Method = $Method
Headers = $headers
Proxy = $proxy
UseBasicParsing = $true
Certificate = $Certificate
}
$datasetJson = Invoke-WebRequest @splatRestMethodParameters -verbose:$false
if (-not[string]::IsNullOrEmpty($certificateBase64)) {
$dataset = $datasetJson.content | ConvertFrom-Json
}
elseif (-not [string]::IsNullOrEmpty($certificatePathertificatePath)) {
$datasetCorrected = [Text.Encoding]::UTF8.GetString([Text.Encoding]::UTF8.GetBytes($datasetJson.content))
$dataset = $datasetCorrected | ConvertFrom-Json
}
else {
Throw "No certificate configured"
}
$result = $dataset.$contentField
if (-not [string]::IsNullOrEmpty($result)) {
$data.value.AddRange($result)
}
}
}
catch {
$data.Value = $null
$ex = $PSItem
if ( $($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObject = Resolve-HTTPError -Error $ex
$verboseErrorMessage = $errorObject.ErrorMessage
$auditErrorMessage = $errorObject.ErrorMessage
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($verboseErrorMessage)) {
$verboseErrorMessage = $ex.Exception.Message
}
if ([String]::IsNullOrEmpty($auditErrorMessage)) {
$auditErrorMessage = $ex.Exception.Message
}
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($verboseErrorMessage)"
throw "Could not query data from ADP. URI: $Url. Error: $auditErrorMessage"
}
}
#endregion functions
# Create Access Token
try {
if (-not[string]::IsNullOrEmpty($certificateBase64)) {
# Use for cloud PowerShell flow
$RAWCertificate = [system.convert]::FromBase64String($certificateBase64)
$Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($RAWCertificate, $certificatePassword)
}
elseif (-not [string]::IsNullOrEmpty($certificatePathertificatePath)) {
# Use for local machine with certificate file
$Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificatePath, $certificatePassword)
}
else {
Throw "No certificate configured"
}
$accessToken = Get-ADPAccessToken -ClientID $clientId -ClientSecret $clientSecret -Certificate $certificate
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($($errorMessage.VerboseErrorMessage))"
throw "Could not create ADP AccessToken. Error Message: $($errorMessage.AuditErrorMessage)"
}
# Query Persons
try {
Write-Verbose "Querying Persons"
$splatADPRestMethodParams = @{
Url = "$BaseUrl/hr/v2/worker-demographics"
Method = 'GET'
AccessToken = $accessToken.access_token
ProxyServer = $ProxyServer
Certificate = $certificate
}
$persons = [System.Collections.ArrayList]::new()
Invoke-ADPRestMethod @splatADPRestMethodParams ([ref]$persons)
# Sort on Medewerker (to make sure the order is always the same)
$persons = $persons | Sort-Object -Property { $_.workerID.idValue }
Write-Information "Succesfully queried Persons. Result count: $($persons.count)"
}
catch {
$ex = $PSItem
if ( $($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObject = Resolve-HTTPError -Error $ex
$verboseErrorMessage = $errorObject.ErrorMessage
$auditErrorMessage = $errorObject.ErrorMessage
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($verboseErrorMessage)) {
$verboseErrorMessage = $ex.Exception.Message
}
if ([String]::IsNullOrEmpty($auditErrorMessage)) {
$auditErrorMessage = $ex.Exception.Message
}
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($verboseErrorMessage)"
throw "Could not query Persons. Error: $auditErrorMessage"
}
# Query Departments
try {
Write-Verbose "Querying Departments"
$splatADPRestMethodParams = @{
Url = "$BaseUrl/core/v1/organization-departments"
Method = 'GET'
AccessToken = $accessToken.access_token
ProxyServer = $ProxyServer
Certificate = $certificate
}
$departments = [System.Collections.ArrayList]::new()
Invoke-ADPRestMethod @splatADPRestMethodParams ([ref]$departments)
# Sort on ExternalId (to make sure the order is always the same)
$departments = $departments | Sort-Object -Property { $_.departmentCode.codeValue }
$departments | Add-Member -MemberType NoteProperty -Name "customFields" -Value ([PSCustomObject]@{}) -Force
$departments | ForEach-Object {
if (($_.auxilliaryFields | Measure-Object).Count -ge 1) {
# Transform auxilliaryFields on departments
foreach ($attribute in $_.auxilliaryFields) {
# Add a property for each field in object
$_.customFields | Add-Member -MemberType NoteProperty -Name "$($attribute.nameCode.codeValue)" -Value "$($attribute.stringValue)" -Force
}
# Remove unneccesary fields from object (to avoid unneccesary large objects and confusion when mapping)
# Remove auxilliaryFields ,since the data is transformed into seperate object
$_.PSObject.Properties.Remove('auxilliaryFields')
}
}
# Group on ExternalId (to match to employments and positions)
$departmentsGrouped = $departments | Group-Object -Property { $_.departmentCode.codeValue } -AsString -AsHashTable
Write-Information "Succesfully queried Departments. Result count: $($departments.count)"
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($($errorMessage.VerboseErrorMessage))"
throw "Could not query Departments. Error Message: $($errorMessage.AuditErrorMessage)"
}
try {
Write-Verbose 'Enhancing and exporting person objects to HelloID'
# Set counter to keep track of actual exported person objects
$exportedPersons = 0
# Enhance person model with required properties
$persons | Add-Member -MemberType NoteProperty -Name "ExternalId" -Value $null -Force
$persons | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $null -Force
$persons | Add-Member -MemberType NoteProperty -Name "Contracts" -Value $null -Force
# Enhance person model with additional properties
$persons | Add-Member -MemberType NoteProperty -Name "BusinessEmail" -Value $null -Force
$persons | Add-Member -MemberType NoteProperty -Name "BusinessLandLine" -Value $null -Force
$persons | Add-Member -MemberType NoteProperty -Name "BusinessMobile" -Value $null -Force
$persons | ForEach-Object {
# Create person object to log on which person the error occurs
$personInProcess = $_
# add empty CustomFields object to person. To be populated with CustomFieldGroup
$_ | Add-Member -MemberType NoteProperty -Name "customFields" -Value ([PSCustomObject]@{}) -Force
# Set required fields for HelloID
$_.ExternalId = $_.workerID.idValue
# Include ExternalId in DisplayName of HelloID Raw Data
$_.DisplayName = $_.person.legalName.formattedName + " ($($_.ExternalId))"
if (($_.businessCommunication | Measure-Object).Count -ge 1) {
# The emails array (if not empty) always contains 1 item
if (($_.businessCommunication.emails | Measure-Object).Count -ge 1) {
$_.BusinessEmail = $_.businessCommunication.emails[0].emailUri
}
# The landlines array (if not empty) always contains 1 item
if (($_.businessCommunication.landLines | Measure-Object).Count -ge 1) {
$_.BusinessLandLine = $_.businessCommunication.landLines[0].formattedNumber
}
# The mobiles array (if not empty) always contains 1 item
if (($worker.businessCommunication.mobiles | Measure-Object).Count -ge 1) {
$_.BusinessMobile = $_.businessCommunication.mobiles[0].formattedNumber
}
# Remove unneccesary fields from object (to avoid unneccesary large objects)
# Remove businessCommunication, since the data is transformed into seperate properties
$_.PSObject.Properties.Remove('businessCommunication')
}
# Transform CustomFields on person
if (($_.customFieldGroup | Measure-Object).Count -ge 1) {
if (($_.customFieldGroup.stringFields | Measure-Object).Count -ge 1) {
foreach ($attribute in $_.customFieldGroup.stringFields) {
# Add a property for each field in object
$_.customFields | Add-Member -MemberType NoteProperty -Name "$($attribute.nameCode.codeValue)" -Value "$($attribute.stringValue)" -Force
}
}
# Remove unneccesary fields from object (to avoid unneccesary large objects)
# Remove customFieldGroup, since the data is transformed into customFields property
$_.PSObject.Properties.Remove('customFieldGroup')
}
$contractsList = [System.Collections.ArrayList]::new()
# Enhance assignments for person
if (($_.workAssignments | Measure-Object).Count -ge 1) {
foreach ($assignment in $_.workAssignments) {
# Set required fields for HelloID
$assignmentExternalId = "$($_.workerID.idValue)" + "_$($assignment.itemID)"
$assignment | Add-Member -MemberType NoteProperty -Name "externalId" -Value $assignmentExternalId -Force
# Transform CustomFields on assigment
$assignment | Add-Member -MemberType NoteProperty -Name "customFields" -Value ([PSCustomObject]@{}) -Force
if (($assignment.customFieldGroup | Measure-Object).Count -ge 1) {
if (($assignment.customFieldGroup.stringFields | Measure-Object).Count -ge 1) {
foreach ($attribute in $assignment.customFieldGroup.stringFields) {
# Add a property for each field in object
$assignment.customFields | Add-Member -MemberType NoteProperty -Name "$($attribute.nameCode.codeValue)" -Value "$($attribute.stringValue)" -Force
}
}
# Remove unneccesary fields from object (to avoid unneccesary large objects)
# Remove customFieldGroup, since the data is transformed into customFields property
$assignment.PSObject.Properties.Remove('customFieldGroup')
}
# Assignments may contain multiple managers (per assignment). There's no way to specify which manager is primary
# We always select the first one in the array
if (($assignment.reportsTo | Measure-Object).Count -ge 1) {
$manager = ($assignment.reportsTo | Sort-Object -Descending)[0]
$assignment | Add-Member -MemberType NoteProperty -Name "manager" -Value $manager -Force
}
if (($assignment.homeOrganizationalUnits | Measure-Object).Count -ge 1) {
# Assignments may contain multiple organizationalUnits (per assignment). There's no way to specify which department is primary
# We always select the last one in the array
$organizationalUnit = ($assignment.homeOrganizationalUnits | Sort-Object -Descending)[-1].nameCode
# Enhance assignments as department for extra information, such as: company
if (($organizationalUnit.codeValue | Measure-Object).Count -ge 1) {
$department = $departmentsGrouped["$($organizationalUnit.codeValue)"]
if (($department | Measure-Object).Count -ge 1) {
# It is possible there are multiple department with the same code, we always select the last on in the array
$organizationalUnit = ($department | Sort-Object -Descending)[-1]
}
}
$assignment | Add-Member -MemberType NoteProperty -Name "organizationalUnit" -Value $organizationalUnit -Force
}
if (($assignment.AssignmentCostCenters | Measure-Object).Count -ge 1) {
# Assignments may contain multiple CostCenters (per assignment). There's no way to specify which department is primary
# We always select the first one in the array
$costCenter = ($assignment.AssignmentCostCenters | Sort-Object -Descending)[0]
$assignment | Add-Member -MemberType NoteProperty -Name "costCenter" -Value $costCenter -Force
}
# Add employment only data to contracts (in case of employments without positions)
[Void]$contractsList.Add($assignment)
}
# Remove unneccesary fields from object (to avoid unneccesary large objects)
# Remove workAssignments, since the data is transformed into the contractsList object
$_.PSObject.Properties.Remove('workAssignments')
}
# Add Contracts to person
if (($contractsList | Measure-Object).Count -ge 1) {
## This example can be used by the consultant if you want to filter out persons with an empty array as contract
## *** Please consult with the Tools4ever consultant before enabling this code. ***
# if ($contractsList.Count -eq 0) {
# Write-Warning "Excluding person from export: $($_.Medewerker). Reason: Contracts is an empty array"
# return
# }
# else {
$_.Contracts = $contractsList
# }
}
## This example can be used by the consultant if the date filters on the person/employment/positions do not line up and persons without a contract are added to HelloID
## *** Please consult with the Tools4ever consultant before enabling this code. ***
# else {
# Write-Warning "Excluding person from export: $($_.Medewerker). Reason: Person has no contract data"
# return
# }
# Sanitize and export the json
$person = $_ | ConvertTo-Json -Depth 10 -Compress
$person = $person.Replace("._", "__")
Write-Output $person
# Updated counter to keep track of actual exported person objects
$exportedPersons++
}
Write-Information "Succesfully enhanced and exported person objects to HelloID. Result count: $($exportedPersons)"
Write-Information "Person import completed"
}
catch {
$ex = $PSItem
if ( $($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObject = Resolve-HTTPError -Error $ex
$verboseErrorMessage = $errorObject.ErrorMessage
$auditErrorMessage = $errorObject.ErrorMessage
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($verboseErrorMessage)) {
$verboseErrorMessage = $ex.Exception.Message
}
if ([String]::IsNullOrEmpty($auditErrorMessage)) {
$auditErrorMessage = $ex.Exception.Message
}
# If debug logging is toggled, log on which person and line the error occurs
if ($c.isDebug -eq $true) {
Write-Warning "Error occurred for person [$($personInProcess.ExternalId)]. Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($VerboseErrorMessage)"
}
throw "Could not enhance and export person objects to HelloID. Error Message: $($auditErrorMessage)"
}