Insert Content into Text File in Powershell

How about this:

(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName

I think that is fairly straight-forward. The only non-obvious thing is the "$&", which refers to what was matched by "pattern". More info: http://www.regular-expressions.info/powershell.html


This problem could be solved by using arrays. A text file is an array of strings. Every element is a line of text.

$FileName = "C:\temp\test.txt"
$Patern = "<patern>" # the 2 lines will be added just after this pattern 
$FileOriginal = Get-Content $FileName

<# create empty Array and use it as a modified file... #>

$FileModified = @() 

Foreach ($Line in $FileOriginal)
{    
    $FileModified += $Line

    if ($Line -match $patern) 
    {
        #Add Lines after the selected pattern 
        $FileModified += 'add text'
        $FileModified += 'add second line text'
    } 
}
Set-Content $fileName $FileModified

Just output the extra text e.g.

(Get-Content $fileName) | 
    Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "pattern") 
        {
            #Add Lines after the selected pattern 
            "Text To Add"
        }
    } | Set-Content $fileName

You may not need the extra ``n` since PowerShell will line terminate each string for you.

Tags:

Powershell