Skip to content

Instantly share code, notes, and snippets.

@dindoliboon
Created June 20, 2017 14:36
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 dindoliboon/b42d793101492b8cb4c0c52edb0497dd to your computer and use it in GitHub Desktop.
Save dindoliboon/b42d793101492b8cb4c0c52edb0497dd to your computer and use it in GitHub Desktop.
Updates simple property files.
function Set-PropertyValue
{
[CmdletBinding()]
param($Path, $Key, $Value, $Separator='=', $Comment="# ", $Backup=$true)
$ini = Get-Content -Path $Path
$newIniPath = [System.IO.Path]::GetTempFileName()
$found = $false
$ini.Split("`n") |% {
$line = $_.Trim()
$iniLine = $line.Split('=')
if ($iniLine.Count -eq 2 -and $iniLine[0].Trim() -like $Key)
{
$found = $true
if ($iniLine[1].Trim() -notlike $Value)
{
if ($Comment.Length -gt 0)
{
Write-Verbose -Message "Updated key [$($Key)] from [$($iniLine[1].Trim())] to [$($Value)]."
($Comment + $line) | Add-Content -Path $newIniPath -Encoding Ascii
}
$line = $iniLine[0].Trim() + $Separator + $Value
}
}
$line | Add-Content -Path $newIniPath -Encoding Ascii
}
if ($found -eq $false)
{
Write-Verbose -Message "New key [$($Key)] = [$($Value)]."
$Key + $Separator + $Value | Add-Content -Path $newIniPath -Encoding Ascii
}
if ($Backup -eq $true)
{
$oldIniPath = $Path + '.BAK.' + (Get-Date).ToFileTimeUtc()
Move-Item -Path $Path -Destination $oldIniPath -Force
Write-Verbose -Message "Old INI has been saved as [$($oldIniPath)]."
}
Move-Item -Path $newIniPath -Destination $Path -Force
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment