Tuesday, 11 September 2012

Working with INI files

Whilst hunting around today for a quick solution for modifying an INI file, I came across tonnes of examples, many half baked.

Found this on Stack-Overflow and it did the trick nicely.


Function Get-IniFile ($file) {
   $iniConfiguration = @{}

   Get-Content $file | foreach {
      $line = $_.split("=")
      $iniConfiguration[$line[0].Trim()] = $line[1].Trim()
   }

   return $iniConfiguration
}

Function Set-IniFile ($iniConfig, $file) {
   Write-Host (New-Item -ItemType file $file -force)

   $iniConfig.Keys | % {
      $fileLine = (" {0}={1}" -f $_,$iniConfig[$_]) 
      Add-Content $file $fileLine
   }
}

# Load the INI file
$iniConfiguration = Get-IniFile $myINIFile

# Modify the properties
$iniConfiguration.port = "80'
$iniConfiguration.hostname = "host.com"   

# Save them back to disk
Set-IniFile $iniConfiguration $myINIFile


Made very easy work of modifying Apache configuration files.

Thought I'd share.


Matt