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?
Usage:
Assuming the
$key
you want to replace is always at the beginning of a line, and that it contains no special regex charactersIf there is no replacement
$key = $value
will be appended to the file.I'd do this:
Edit: added a replacement bell, and a not match whistle.
@CarlR Function it's for PowerShell Version 3. This it's the same adapted to PowerShell Version 2.
EDIT: Changed regular expression to fix two bugs on Set-FileConfigurationValue:
If you have one line like this:
; This is a Black line
And you try to do:
Set-FileConfigurationValue $configFile "Black" 20 -ReplaceExistingValue
You get one message about "Replacing" but nothing happens.
If you have two lines like these:
filesTmp=50
Tmp=50
And you try to do:
Set-FileConfigurationValue $configFile "Tmp" 20 -ReplaceExistingValue
You get the two lines changed!
filesTmp=20 Tmp=20
This is the final version:
I've also added a function to read from the config file
Change the function to this:
Then when you call the function, use this format:
Edit: I forgot your requirement of adding the line if it doesn't exist. This will check for the
$key
, if it exists it will set its value to$value
. If it doesn't exist it will add$key = $value
to the end of the file. I also renamed the function to be more consistent with power shell naming conventions.Updated version of the functions above with some parametrisation and verbose output if required.