Add and remove lines in text based config files with PowerShell

7. April 2017

blog.feldmann.io

PowerShell Version: >4 
Modules: none

I want to take some text file and look for a specific line, then delete that line and add some other line at the end of the file. Here’s how I made it work:

# define file for input/output
$outfile = "C:\test.properties"
# set line to be removed
$old_content = 'install=1'
# set line to be added
$new_content = 'install=0'

#check if new line is already in place and then skip
$check = get-content $outfile | select-string -pattern $new_content
if (!$check)
    {
    #use temporary variable for enabling overwrite
    $tmp = get-content $outfile | select-string -pattern $old_content -notmatch
    $tmp | Set-Content $outfile
    # add new content at the end of the file
    $new_content | Out-File $outfile -Append ascii
    }
#PowerShell
1 Comment
29. June 2017 @ 11:11

This is exactly what I was looking for. Works great! Many thanks for sharing.

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*