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.
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*"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With