Private/Ini.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
#https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/

function Get-IniContent {
    Param(
        [String]$FilePath
    )
    $ini = @{}
    switch -regex -file $FilePath
    {
        '^\[(.+)\]' # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }
        '^(;.*)$' # Comment
        {
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = 'Comment' + $CommentCount
            $ini[$section][$name] = $value
        }
        '(.+?)\s*=(.*)' # Key
        {
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }
    return $ini
}

function Out-IniFile {
    Param(
        [Hashtable]$InputObject,
        [String]$FilePath
    )

    foreach ($i in $InputObject.keys)
    {
        if (!($($InputObject[$i].GetType().Name) -eq 'Hashtable'))
        {
            #No Sections
            Add-Content -Path $FilePath -Value "$i=$($InputObject[$i])"
        } else {
            #Sections
            Add-Content -Path $FilePath -Value "[$i]"
            Foreach ($j in ($InputObject[$i].keys | Sort-Object))
            {
                if ($j -match '^Comment[\d]+') {
                    Add-Content -Path $FilePath -Value "$($InputObject[$i][$j])"
                } else {
                    Add-Content -Path $FilePath -Value "$j=$($InputObject[$i][$j])"
                }

            }
            Add-Content -Path $FilePath -Value ''
        }
    }
}