Powershell function to replace or add lines in text files
append, powershell, regex, replace
Solution
Assuming the `$key` you want to replace is always at the beginning of a line, and that it contains no special regex characters
function setConfig( $file, $key, $value ) {
$content = Get-Content $file
if ( $content -match "^$key\s*=" ) {
$content -replace "^$key\s*=.*", "$key = $value" |
Set-Content $file
} else {
Add-Content $file "$key = $value"
}
}
setConfig "divider.conf" "Logentrytimeout" "180"
If there is no replacement `$key = $value` will be appended to the file.
Problem
I'm working on a powershell script that modifies config files. I have files like this: ``` ##################################################### # comment about logentrytimeout ##################################################### Logentrytimeout= 1800 ``` who should look like this: ``` ##################################################### # comment about logentrytimeout ##################################################### Logentrytimeout= 180 disablepostprocessing = 1 segmentstarttimeout = 180 ``` If there is a key set(Logentrytimeout), just update it to the given value. Ignore comments, where the key is mentioned(lines that start with #). The Key is case insensitive. If the key is not set(disablepostprocessing and segmentstarttimeout), append key and value to the file. My function so far goes like this: ``` function setConfig( $file, $key, $value ) { (Get-Content $file) | Foreach-Object {$_ -replace "^"+$key+".=.+$", $key + " = " + $value } | Set-Content $file } setConfig divider.conf "Logentrytimeout" "180" setConfig divider.conf "disablepostprocessing" "1" setConfig divider.conf "segmentstarttimeout" "180" ``` - What is the correct regex? - How do I check if there was a replacement? - If there was no replacement: How can I append $key+" = "+$value to the file then?