Created
June 3, 2020 21:25
-
-
Save codaamok/7ea4404bd30efdd6934f6a08940880c0 to your computer and use it in GitHub Desktop.
Using StringBuilder class, create a multi line string in typical .ini format from an array of hash tables or ordered dictionaries.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ConvertTo-Ini { | |
param ( | |
[Object[]]$Content, | |
[String]$SectionTitleKeyName | |
) | |
begin { | |
$StringBuilder = [System.Text.StringBuilder]::new() | |
$SectionCounter = 0 | |
} | |
process { | |
foreach ($ht in $Content) { | |
$SectionCounter++ | |
if ($ht -is [System.Collections.Specialized.OrderedDictionary] -Or $ht -is [hashtable]) { | |
if ($ht.Keys -contains $SectionTitleKeyName) { | |
$null = $StringBuilder.AppendFormat("[{0}]", $ht[$SectionTitleKeyName]) | |
} | |
else { | |
$null = $StringBuilder.AppendFormat("[Section {0}]", $SectionCounter) | |
} | |
$null = $StringBuilder.AppendLine() | |
foreach ($key in $ht.Keys) { | |
if ($key -ne $SectionTitleKeyName) { | |
$null = $StringBuilder.AppendFormat("{0}={1}", $key, $ht[$key]) | |
$null = $StringBuilder.AppendLine() | |
} | |
} | |
$null = $StringBuilder.AppendLine() | |
} | |
} | |
} | |
end { | |
$StringBuilder.ToString(0, $StringBuilder.Length-4) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment