Skip to content

Instantly share code, notes, and snippets.

@codaamok
Created June 3, 2020 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codaamok/7ea4404bd30efdd6934f6a08940880c0 to your computer and use it in GitHub Desktop.
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.
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