-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdepartments.ps1
196 lines (157 loc) · 7.5 KB
/
departments.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
#####################################################
# HelloID-Conn-Prov-Source-AFAS-Profit-Departments
#
# Version: 2.0.0.2
#####################################################
# 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
$VerbosePreference = "SilentlyContinue"
$InformationPreference = "Continue"
$WarningPreference = "Continue"
$c = $configuration | ConvertFrom-Json
$baseUri = $($c.BaseUrl)
$token = $($c.Token)
# Set debug logging
switch ($($c.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
Write-Information "Start department import: Base URL: $baseUri, Using positionsAction: $positionsAction, token length: $($token.length)"
#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-AFASConnectorData {
param(
[parameter(Mandatory = $true)]$Token,
[parameter(Mandatory = $true)]$BaseUri,
[parameter(Mandatory = $true)]$Connector,
[parameter(Mandatory = $true)]$OrderByFieldIds,
[parameter(Mandatory = $true)][ref]$data
)
try {
Write-Verbose "Starting downloading objects through get-connector [$connector]"
$encodedToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Token))
$authValue = "AfasToken $encodedToken"
$Headers = @{ Authorization = $authValue }
$Headers.Add("IntegrationId", "45963_140664") # Fixed value - Tools4ever Partner Integration ID
$take = 1000
$skip = 0
$uri = $BaseUri + "/connectors/" + $Connector + "?skip=$skip&take=$take&orderbyfieldids=$OrderByFieldIds"
$dataset = Invoke-RestMethod -Method Get -Uri $uri -Headers $Headers -UseBasicParsing
foreach ($record in $dataset.rows) { [void]$data.Value.add($record) }
$skip += $take
while (@($dataset.rows).count -eq $take) {
$uri = $BaseUri + "/connectors/" + $Connector + "?skip=$skip&take=$take&orderbyfieldids=$OrderByFieldIds"
$dataset = Invoke-RestMethod -Method Get -Uri $uri -Headers $Headers -UseBasicParsing
$skip += $take
foreach ($record in $dataset.rows) { [void]$data.Value.add($record) }
}
Write-Verbose "Downloaded [$($data.Value.count)] records through get-connector [$connector]"
}
catch {
$data.Value = $null
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
throw "Error querying data from [$uri]. Error Message: $($errorMessage.AuditErrorMessage)"
}
}
#endregion functions
# Query OrganizationalUnits
try {
Write-Information 'Querying OrganizationalUnits'
$organizationalUnits = [System.Collections.ArrayList]::new()
Get-AFASConnectorData -Token $token -BaseUri $baseUri -Connector "T4E_HelloID_OrganizationalUnits_v2" -OrderByFieldIds "ExternalId" ([ref]$organizationalUnits)
# Sort on ExternalId (to make sure the order is always the same)
$organizationalUnits = $organizationalUnits | Sort-Object -Property ExternalId
Write-Information "Successfully queried OrganizationalUnits. Result count: $($organizationalUnits.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 OrganizationalUnits. Error Message: $($errorMessage.AuditErrorMessage)"
}
try {
Write-Information 'Enhancing and exporting department objects to HelloID'
# Set counter to keep track of actual exported department objects
$exportedDepartments = 0
$organizationalUnits | ForEach-Object {
# Create department object to log on which department the error occurs
$departmentInProcess = $_
# Create department object to ensure only allowed properties are send to HelloID
$departmentObject = [PSCustomObject]@{
ExternalId = $_.ExternalId
DisplayName = $_.DisplayName
ManagerExternalId = $_.ManagerExternalId
ParentExternalId = $_.ParentExternalId
}
# Sanitize and export the json
$departmentObject = $departmentObject | ConvertTo-Json -Depth 10
Write-Output $departmentObject
# Updated counter to keep track of actual exported department objects
$exportedDepartments++
}
Write-Information "Successfully enhanced and exported department objects to HelloID. Result count: $($exportedDepartments)"
Write-Information "Department import completed"
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
# If debug logging is toggled, log on which department and line the error occurs
if ($c.isDebug -eq $true) {
Write-Warning "Error occurred for department [$($departmentInProcess.ExternalId)]. Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
}
throw "Could not enhance and export department objects to HelloID. Error Message: $($errorMessage.AuditErrorMessage)"
}