internal/functions/configuration/Read-PsfConfigFile.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
function Read-PsfConfigFile
{
<#
 .SYNOPSIS
  Reads a configuration file and parses it.
  
 .DESCRIPTION
  Reads a configuration file and parses it.
  
 .PARAMETER Path
  The path to the file to parse.
  
 .EXAMPLE
  PS C:\> Read-PsfConfigFile -Path config.json
  
  Reads the config.json file and returns interpreted configuration objects.
#>

    [CmdletBinding()]
    param (
        [string]
        $Path
    )
    
    #region Utility Function
    function New-ConfigItem
    {
        [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
        [CmdletBinding()]
        param (
            $FullName,
            
            $Value,
            
            $Type,
            
            [switch]
            $KeepPersisted,
            
            [switch]
            $Enforced,
            
            [switch]
            $Policy
        )
        
        [pscustomobject]@{
            FullName        = $FullName
            Value            = $Value
            Type            = $Type
            KeepPersisted   = $KeepPersisted
            Enforced        = $Enforced
            Policy            = $Policy
        }
    }
    #endregion Utility Function
    
    if (-not (Test-Path $Path)) { return }
    
    $data = Get-Content -Path $Path -Encoding UTF8 | ConvertFrom-Json
    foreach ($item in $data)
    {
        #region No Version
        if (-not $item.Version)
        {
            New-ConfigItem -FullName $item.FullName -Value ([PSFramework.Configuration.ConfigurationHost]::ConvertFromPersistedValue($item.Value, $item.Type))
        }
        #endregion No Version
        
        #region Version One
        if ($item.Version -eq 1)
        {
            if ($item.Style -eq "Simple") { New-ConfigItem -FullName $item.FullName -Value $item.Data }
            else
            {
                if ($item.Type -eq "Object")
                {
                    New-ConfigItem -FullName $item.FullName -Value $item.Data -Type "Object" -KeepPersisted
                }
                else
                {
                    New-ConfigItem -FullName $item.FullName -Value ([PSFramework.Configuration.ConfigurationHost]::ConvertFromPersistedValue($item.Value, $item.Type))
                }
            }
        }
        #endregion Version One
    }
}