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

Leave a Reply

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


*