|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | + Convert the INI file content to a hashtable containing the configuration. |
| 4 | +
|
| 5 | +.DESCRIPTION |
| 6 | + Convert the INI file content to a hashtable containing the configuration. |
| 7 | +
|
| 8 | +.PARAMETER Content |
| 9 | + An array of strings with the INI file content. Each array item is a line. |
| 10 | +
|
| 11 | +.EXAMPLE |
| 12 | + C:\> Get-Content -Path 'config.ini' | ConvertFrom-ScriptConfigIni |
| 13 | + Use the pipeline input to parse the INI file content. |
| 14 | +#> |
| 15 | + |
| 16 | +function ConvertFrom-ScriptConfigIni |
| 17 | +{ |
| 18 | + [CmdletBinding()] |
| 19 | + param |
| 20 | + ( |
| 21 | + [Parameter(Position=0, |
| 22 | + Mandatory=$true, |
| 23 | + ValueFromPipeline=$true)] |
| 24 | + [AllowEmptyString()] |
| 25 | + [String[]] $Content |
| 26 | + ) |
| 27 | + |
| 28 | + Write-Verbose "Parse script configuration file as INI format ..." |
| 29 | + |
| 30 | + $Config = @{} |
| 31 | + |
| 32 | + try |
| 33 | + { |
| 34 | + # Iterating each line and parse the setting |
| 35 | + foreach ($Line in $Content) |
| 36 | + { |
| 37 | + switch -Wildcard ($Line) |
| 38 | + { |
| 39 | + # Comment |
| 40 | + ';*' { |
| 41 | + |
| 42 | + break |
| 43 | + } |
| 44 | + |
| 45 | + # Array |
| 46 | + '*`[`]=*'{ |
| 47 | + $Key = $Line.Split('[]=', 4)[0] |
| 48 | + $Value = $Line.Split('[]=', 4)[3] |
| 49 | + |
| 50 | + if ($null -eq $Config[$Key]) |
| 51 | + { |
| 52 | + $Config[$Key] = @() |
| 53 | + } |
| 54 | + |
| 55 | + $Config[$Key] += $Value |
| 56 | + |
| 57 | + break |
| 58 | + } |
| 59 | + |
| 60 | + # Hashtable |
| 61 | + '*`[*`]=*' { |
| 62 | + $Key = $Line.Split('[]=', 4)[0] |
| 63 | + $Hash = $Line.Split('[]=', 4)[1] |
| 64 | + $Value = $Line.Split('[]=', 4)[3] |
| 65 | + |
| 66 | + if ($null -eq $Config[$Key]) |
| 67 | + { |
| 68 | + $Config[$Key] = @{} |
| 69 | + } |
| 70 | + |
| 71 | + $Config[$Key][$Hash] = $Value |
| 72 | + |
| 73 | + break |
| 74 | + } |
| 75 | + |
| 76 | + # String, Integer or Boolean |
| 77 | + '*=*' { |
| 78 | + $Key = $Line.Split('=', 2)[0] |
| 79 | + $Value = $Line.Split('=', 2)[1] |
| 80 | + |
| 81 | + try { $Value = [Int32]::Parse($Value) } catch { } |
| 82 | + |
| 83 | + if ('True'.Equals($Value)) { $Value = $true } |
| 84 | + if ('False'.Equals($Value)) { $Value = $false } |
| 85 | + |
| 86 | + $Config[$Key] = $Value |
| 87 | + |
| 88 | + break |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + Write-Output $Config |
| 94 | + } |
| 95 | + catch |
| 96 | + { |
| 97 | + throw "The configuration file content was in an invalid format: $_" |
| 98 | + } |
| 99 | +} |
0 commit comments