If you are rewriting the entire file and you don't need to keep the comments you can use the load syntax here, https://stackoverflow.com/a/20276315/3794873 and then the write syntax here, https://stackoverflow.com/a/35210799/3794873 but mind the notes about losing ordering.
If you need to keep the original order, see the other answer using -replace
, or create an OrderedDict in PowerShell and populate it via a loop over the lines in the file (see example in code below).
I've condensed the linked question and answer above in the example below.
$filename = 'myfile.properties'
$filedata = @'
app.name=Test App
app.version=1.2
app.data=Some words
'@
$filedata | set-content $filename
# This method doesn't maintain ordering
$fileProps = convertfrom-stringdata (Get-Content $filename | Out-String)
#could use also use -raw in PS 3 or higher instead of | Out-String
Write-Output "Initial data"
$fileProps.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Write-Output
$fileProps['app.name'] = 'StringData App'
Write-Output "Updated data"
$fileProps.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Write-Output
$fileProps.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Out-File .\myfile.stringdata.properties -Encoding "ASCII"
# This method uses an ordered dict to maintain... order
$dict = [ordered]@{}
Get-Content $filename | foreach-object {$dict.add($_.split('=',2)[0],$_.split('=',2)[1])}
Write-Output "Initial data"
$dict.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Write-Output
$dict['app.name'] = 'Ordered Dict App'
Write-Output "Updated data"
$dict.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Write-Output
$dict.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } | Out-File .\myfile.ordered.properties -Encoding "ASCII"