Created
June 20, 2017 14:36
-
-
Save dindoliboon/b42d793101492b8cb4c0c52edb0497dd to your computer and use it in GitHub Desktop.
Updates simple property files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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