Skip to content

Instantly share code, notes, and snippets.

@hsmalley
Created October 4, 2012 20:53
Show Gist options
  • Save hsmalley/3836383 to your computer and use it in GitHub Desktop.
Save hsmalley/3836383 to your computer and use it in GitHub Desktop.
Powershell to/from INI Files
function Get-IniContent ($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($InputObject, $FilePath)
{
$outFile = New-Item -ItemType file -Path $Filepath
foreach ($i in $InputObject.keys)
{
if (!($($InputObject[$i].GetType().Name) -eq "Hashtable"))
{
#No Sections
Add-Content -Path $outFile -Value "$i=$($InputObject[$i])"
} else {
#Sections
Add-Content -Path $outFile -Value "[$i]"
Foreach ($j in ($InputObject[$i].keys | Sort-Object))
{
if ($j -match "^Comment[\d]+") {
Add-Content -Path $outFile -Value "$($InputObject[$i][$j])"
} else {
Add-Content -Path $outFile -Value "$j=$($InputObject[$i][$j])"
}
}
Add-Content -Path $outFile -Value ""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment