private/Read-JsonConfigFile.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
function Read-JsonConfigFile {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)] [string] $Path,
        [Parameter(Mandatory)] [Adf] $adf,
        [Parameter(Mandatory)] [AdfPublishOption] $option
    )

    Write-Debug "BEGIN: Read-JsonConfigFile(path=$path)"
    $configFileName = $Path

    Write-Debug "Testing config file..."
    Test-Path -Path $configFileName -PathType Leaf | Out-Null 

    #$configFileName = "X:\!WORK\GitHub\!SQLPlayer\azure.datafactory.tools\test\BigFactorySample2\deployment\config-c100.json"
    $configtxt = Get-Content  $configFileName -Raw | Out-String
    $json = ConvertFrom-Json $configtxt 

    # Creating CSV-like an object
    [System.Collections.ArrayList] $config = @{}

    Set-StrictMode -Version 1.0     # Due to field 'action' which may not exist
    $json.psobject.properties.name | ForEach-Object {
        $name = $_
        $o = $json.($name)
        $o | ForEach-Object {
            $dst = $adf.AllObjects() | Where-Object { $_.Name -eq $name } | Select-Object -First 1
            if ($null -ne $dst) {
                $cl = New-Object -TypeName ConfigLine
                $cl.name = $name
                $cl.type = $dst.Type
                $cl.value = $_.value
                $cl.path = $_.name
                if ($_.action -eq "remove") { $cl.path = "-$($cl.path)" }
                if ($_.action -eq "add") { $cl.path = "+$($cl.path)" }
                $null = $config.Add($cl)
            } else {
                if ($option.FailsWhenConfigItemNotFound -eq $false) {
                    Write-Warning "Object [$name] could not be found, skipping..."
                } else {
                    Write-Error "Object [$name] could not be found."
                }
            }
        }
    }

    # Expanding string (replace Environment Variables with values)
    $config | ForEach-Object {
        $_.value = $ExecutionContext.InvokeCommand.ExpandString($_.value);
    }

    return $config.ToArray()

    Write-Debug "END: Read-JsonConfigFile"

}