Functions/LabEnvironment/Get-LabEnvironment.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
#Requires -Version 5.0

function Get-LabEnvironment {
    [CmdletBinding(DefaultParameterSetName = 'EnvironmentName')]
    param (
        [Parameter(Mandatory = $false, Position = 0, ParameterSetName = 'EnvironmentName')]
        [string[]]$Name,
        [Parameter(Mandatory = $true, ParameterSetName = 'EnvironmentPath')]
        [string[]]$Path
    )

    $filePaths = @()
    if ($($PSCmdlet.ParameterSetName) -eq 'EnvironmentName') {
        $environmentsFilePath = Join-Path -Path $script:configurationPath -ChildPath 'environments.json'
        if (Test-Path -Path $environmentsFilePath -PathType Leaf) {
            $environments = Get-Content -Path $environmentsFilePath -Raw | ConvertFrom-Json | Convert-PSObjectToHashtable
            foreach ($environmentName in $environments.Keys) {
                if (-not $Name -or $Name -contains $environmentName) {
                    $filePaths += $environments.$environmentName
                }                
            }
        }
    }
    else {
        foreach ($p in $Path) {
            $filePaths += $p
        }
    }

    foreach ($filePath in $filePaths) {
        $environmentFilePath = $filePath
        Write-Verbose "Processing path '$environmentFilePath'"

        if (Test-Path -Path $environmentFilePath -PathType Container) {
            Write-Verbose "path '$environmentFilePath' is folder, assuming filename is missing"
            $environmentFilePath = Join-Path -Path $environmentFilePath -ChildPath 'environment.json'
        }

        if (Test-Path -Path $environmentFilePath -PathType Leaf) {
            Write-Verbose "file '$environmentFilePath' found"
            $environmentContent = Get-Content -Path $environmentFilePath -Raw

            $tokensFilePath = [System.IO.Path]::GetFullPath((Join-Path -Path (Split-Path -Path $environmentFilePath -Parent) -ChildPath 'tokens.json'))
            if (Test-Path -Path $tokensFilePath -PathType Leaf) {
                $tokens = Get-Content -Path $tokensFilePath -Raw | ConvertFrom-Json | Convert-PSObjectToHashtable
                foreach ($key in $tokens.Keys) {
                    try {
                        $environmentContent = $environmentContent.Replace("{$key}", ($tokens.$key))
                    }
                    catch {
                        Write-Warning -Message "Error replacing token '$key'."
                    }
                }
            }

            $environment = Convert-FromJsonObject -InputObject ($environmentContent | ConvertFrom-Json) -TypeName 'LabEnvironment'
            if (-not $Name -or $Name -contains $environment.Name) {
                $environment.Path = $environmentFilePath

                Write-Output $environment
            }
        }
    }
}