Skip to content

Instantly share code, notes, and snippets.

@winkler-winsen
Created October 5, 2023 11:44
Show Gist options
  • Select an option

  • Save winkler-winsen/3c3242bb9bdf78289fe80396408c2fcf to your computer and use it in GitHub Desktop.

Select an option

Save winkler-winsen/3c3242bb9bdf78289fe80396408c2fcf to your computer and use it in GitHub Desktop.
PowerShell INI file input output
# source: https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/
# alternatively you can use PsINI Module https://www.powershellgallery.com/packages/PsIni/3.1.2
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 “”
}
}
}
$IniFile = Get-IniContent ".\sample.ini"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment