Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Content into specific place in Text File in Powershell

Tags:

powershell

I want to add content into the specific place of a text file in Powershell. I tried with Add Content but it is adding text at the end of the file.

like image 854
varun Avatar asked Sep 18 '25 00:09

varun


1 Answers

Here's one way you could do this. Basically just store the entire file in a variable, and then loop through all of the lines to find where you want to insert the new line of text (in my case I'm determining this based off of search criteria). Then write that new file output back to the file, overwriting it:

$FileContent = 
    Get-ChildItem "C:\temp\some_file.txt" |
        Get-Content

$FileContent
<#
this is the first line
this is the second line
this is the third line
this is the fourth line
#>

$NewFileContent = @()

for ($i = 0; $i -lt $FileContent.Length; $i++) {
    if ($FileContent[$i] -like "*second*") {
        # insert your line before this line
        $NewFileContent += "This is my newly inserted line..."
    }

    $NewFileContent += $FileContent[$i]
}

$NewFileContent |
    Out-File "C:\temp\some_file.txt"

Get-ChildItem "C:\temp\some_file.txt" |
    Get-Content
<#
this is the first line
This is my newly inserted line...
this is the second line
this is the third line
this is the fourth line
#>

In my example above, I'm using the following conditional test for a particular line to test whether or not the new line should be inserted:

$FileContent[$i] -like "*second*"
like image 150
Thomas Stringer Avatar answered Sep 19 '25 19:09

Thomas Stringer