Saturday, April 15, 2017

Add and remove lines in text based config files with PowerShell

Add and remove lines in text based config files with PowerShell

http://ift.tt/2oHSpee

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

# 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

Powershell

via Planet PowerShell http://ift.tt/2ozzxeJ

April 6, 2017 at 05:56PM

No comments:

Post a Comment