Helpers/ConvertFrom-ScriptConfigIni.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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
<#
.SYNOPSIS Convert the INI file content to a hashtable containing the configuration. .EXAMPLE PS C:\> Get-Content -Path 'config.ini' | ConvertFrom-ScriptConfigIni Use the pipeline input to parse the INI file content. .NOTES Author : Claudio Spizzi License : MIT License .LINK https://github.com/claudiospizzi/ScriptConfig #> function ConvertFrom-ScriptConfigIni { [CmdletBinding()] param ( # An array of strings with the INI file content. [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [AllowEmptyString()] [System.String[]] $Content ) $config = @{ PSTypeName = 'ScriptConfig.Configuration' } try { # Iterating each line and parse the setting foreach ($line in $Content) { switch -Wildcard ($line) { # Comment ';*' { break } # Section '`[*`]*' { break } # Array '*`[`]=*'{ $key = $line.Split('[]=', 4)[0] $value = $line.Split('[]=', 4)[3] if ($null -eq $config[$key]) { $config[$key] = @() } $config[$key] += $value break } # Hashtable '*`[*`]=*' { $key = $line.Split('[]=', 4)[0] $hash = $line.Split('[]=', 4)[1] $value = $line.Split('[]=', 4)[3] if ($null -eq $config[$key]) { $config[$key] = @{} } $config[$key][$hash] = $value break } # String, Integer or Boolean '*=*' { $key = $line.Split('=', 2)[0] $value = $line.Split('=', 2)[1] [Int32] $valueInt = $null if (([Int32]::TryParse($value, [ref] $valueInt))) { $config[$key] = $valueInt } else { if ('True'.Equals($value)) { $value = $true } if ('False'.Equals($value)) { $value = $false } $config[$key] = $value } break } } } [PSCustomObject] $config } catch { throw "The INI configuration file content was in an invalid format: $_" } } |