Powershell function to replace or add lines in text files

Question:

I’m working on a powershell script that modifies config files. I have files like this:

who should look like this:

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:

  • 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?

Answer:

Assuming the $key you want to replace is always at the beginning of a line, and that it contains no special regex characters

If there is no replacement $key = $value will be appended to the file.

Source:

Powershell function to replace or add lines in text files by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply