-
Notifications
You must be signed in to change notification settings - Fork 0
/
departments.ps1
174 lines (153 loc) · 5.98 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
#####################################################
# HelloID-Conn-Prov-Source-SDBHR
#
# Version: 2.0.0.0
# Updated to output data record by record
#####################################################
$VerbosePreference = "Continue"
$config = $Configuration | ConvertFrom-Json
$ApiUser = $($config.ApiUser)
$ApiKey = $($config.ApiKey)
$KlantNummer = $($config.KlantNummer)
$BaseUrl = $($config.BaseUrl)
#region Helper Functions
function New-SDBHRCalculatedHash {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$ApiKey,
[Parameter(Mandatory)]
[string]
$KlantNummer,
[Parameter(Mandatory)]
[string]
$CurrentDateTime
)
try {
Write-Verbose 'Calculating SDHBR hash'
$baseString = "$($CurrentDateTime.Substring(0,10))|$($CurrentDateTime.Substring(11,12))|$KlantNummer"
$key = [System.Text.Encoding]::UTF8.GetBytes($ApiKey)
$hmac256 = [System.Security.Cryptography.HMACSHA256]::new()
$hmac256.key = $key
$hash = $hmac256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($baseString))
$hashedString = [System.Convert]::ToBase64String($hash)
Write-Output $hashedString
}
catch {
$PScmdlet.ThrowTerminatingError($_)
}
}
function Invoke-SDBHRRestMethod {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Uri,
[Parameter(Mandatory)]
[System.Collections.IDictionary]
$Headers
)
process {
try {
Write-Verbose "Invoking command '$($MyInvocation.MyCommand)' to Uri '$Uri'"
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::tls12
$splatRestMethodParameters = @{
Uri = $Uri
Method = 'Get'
ContentType = 'application/json'
Headers = $Headers
}
Invoke-RestMethod @splatRestMethodParameters
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
}
function Resolve-HTTPError {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$HttpErrorObj = @{
FullyQualifiedErrorId = $ErrorObject.FullyQualifiedErrorId
InvocationInfo = $ErrorObject.InvocationInfo.MyCommand
TargetObject = $ErrorObject.TargetObject.RequestUri
}
if ($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') {
$HttpErrorObj['ErrorMessage'] = $ErrorObject.ErrorDetails.Message
}
elseif ($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException') {
$stream = $ErrorObject.Exception.Response.GetResponseStream()
$stream.Position = 0
$streamReader = [System.IO.StreamReader]::new($Stream)
$errorResponse = $StreamReader.ReadToEnd()
$HttpErrorObj['ErrorMessage'] = $errorResponse
}
Write-Output "'$($HttpErrorObj.ErrorMessage)', TargetObject: '$($HttpErrorObj.TargetObject), InvocationCommand: '$($HttpErrorObj.InvocationInfo)"
}
}
#endregion Helper Functions
try {
$currentDateTime = (Get-Date).ToString("dd-MM-yyyy HH:mm:ss.fff")
$hashedString = New-SDBHRCalculatedHash -ApiKey $ApiKey -KlantNummer $KlantNummer -CurrentDateTime $currentDateTime
Write-Verbose 'Adding Authorization headers'
$headers = [System.Collections.Generic.Dictionary[[String], [String]]]::new()
$headers.Add("Content-Type", "application/json")
$headers.Add("Timestamp", $currentDateTime)
$headers.Add("Klantnummer", $klantnummer)
$headers.Add("Authentication", "$($ApiUser):$($hashedString)")
$headers.add("Api-Version", "2.0")
Write-Verbose 'Retrieving departments data'
$departmentsList = [System.Collections.generic.List[object]]::new()
$splatParams = @{
Uri = "$BaseUrl/api/afdelingen"
Headers = $headers
}
$departmentsResponse = Invoke-SDBHRRestMethod @splatParams
$departmentsList.AddRange($departmentsResponse)
Write-Verbose "Found $($departmentsResponse.Count) departments. Creating list of departments to return"
# $departmentsList = $departmentsList | Select-Object *, @{name = 'ExternalId'; expression = { $_.Code } }, @{name = 'DisplayName'; expression = { $_.Omschrijving } }
foreach ($record in $departmentsList) {
# Department can have multiple managers, therefore we sort on id and then select the first, if no manager is provided, we leave the ManagerExternalId emtpy
if ($null -ne $record.Leidinggevenden) {
$manager = $record.Leidinggevenden | Sort-Object -Property Id | Select-Object -First 1
if (-not[string]::IsNullOrEmpty($manager)) {
$managerExternalId = $manager.Id
}
else {
$managerExternalId = $null
}
}
else {
$managerExternalId = $null
}
# Department can have no parent department, therefore we check if there is a parent department, if not we leave the ParentExternalId empty
if ($null -ne $record.HoofdAfdeling) {
$parentExternalId = $record.HoofdAfdeling.Code
}
else {
$parentExternalId = $null
}
$department = [PSCustomObject]@{
ExternalId = $record.Code
ShortName = $record.Omschrijving
DisplayName = $record.Omschrijving
ManagerExternalId = $managerExternalId
ParentExternalId = $parentExternalId
}
# Sanitize and export the json
$department = $department | ConvertTo-Json -Depth 10
$department = $department.Replace("._", "__")
Write-Output $department
}
}
catch {
throw $_
}