functions/general/Load-TmfConfiguration.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
function Load-TmfConfiguration
{
    <#
        .SYNOPSIS
            Loads the JSON files from the activated configurations.
        .DESCRIPTION
            Loads the JSON files from the activated configurations.
            All object definitions are stored in runtime variables.
        .PARAMETER ReturnDesiredConfiguration
            Returns the desired configuration after loading from activated configurations.
    #>

    [CmdletBinding()]
    Param (
        [switch] $ReturnDesiredConfiguration
    )
    
    begin
    {    
        $configurationsToLoad = Get-TmfActiveConfiguration
        $script:desiredConfiguration = @{}
    }
    process
    {
        foreach ($configuration in $configurationsToLoad) {
            $resourceDirectories = Get-ChildItem $configuration.Path -Directory -Recurse
            foreach ($resourceDirectory in $resourceDirectories) {                
                if ($resourceDirectory.Name -notin $script:supportedResources.Keys) {
                    Write-PSFMessage -Level Verbose -String "Load-TmfConfiguration.NotSupportedComponent" -StringValues $resourceDirectory.Name, $configuration.Name
                    continue
                }
                if ("registerFunction" -notin $script:supportedResources[$resourceDirectory.Name].Keys) { continue }
                
                if (-Not $script:desiredConfiguration.ContainsKey($resourceDirectory.Name)) {
                    $script:desiredConfiguration[$resourceDirectory.Name] = @()
                }                
                Get-ChildItem -Path $resourceDirectory.FullName -File -Filter "*.json" | ForEach-Object {
                    $content = Get-Content $_.FullName | ConvertFrom-Json
                    if ($content.count -gt 0) {
                        $content | Foreach-Object {
                            $resource = $_ | Add-Member -NotePropertyMembers @{sourceConfig = $configuration.Name} -PassThru | ConvertTo-PSFHashtable -Include $($script:supportedResources[$resourceDirectory.Name]["registerFunction"].Parameters.Keys)
                            # Calls the Register-Tmf(.*) function
                            & $script:supportedResources[$resourceDirectory.Name]["registerFunction"] @resource -Cmdlet $PSCmdlet
                        }
                    }                     
                }
            }
        }
    }
    end
    {
        if ($ReturnDesiredConfiguration) {
            Get-TmfDesiredConfiguration
        }        
    }
}