Powershell - Adding a line to a file from a specific line

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

Having switched from a database-driven CMS site to a Markdown file-based site, I needed to modify what is known as the frontmatter.

A section at the beginning of the Markdown file containing information about the article (date, title, etc.).

The easiest way to do this is to use a collection (collection, arraylist, genericlist) that contains an .insert() method.

Here are a few examples of how to add a line to a specific location in a file (you know the line number where you want to place your text content)

## From an arraylist
# File path
$Path = 'c:\Path_File'
# Content to add
$TextToAdd = "lang: en"
# List files
$Files = Get-ChildItem -path $Path -File
# Loop for each file
foreach ( $File in $Files ) {
# Load the contents of the file
[System.Collections.ArrayList]$FileContent1 = get-content $File.FullName
# Add content
# 7 corresponds to an addition on the 8th line
$FileContent1.Insert(7,$TextToAdd)
# Modify the file
Set-Content -Path $File.FullName -Value $FileContent1
}
## From a Generic List
# File path
$Path = 'c:\Path_File'
# Content to add
$TextToAdd = "lang: en"
# List files
$Files = Get-ChildItem -path $Path -File
# Loop for each file
foreach ( $File in $Files ) {
# Load the contents of the file
[System.Collections.Generic.List[String]]$FileContent2 = get-content $File.FullName
# Add content
# 7 corresponds to an addition to the 8th line
$FileContent2.Insert(7,$TextToAdd)
# Modify the file
Set-Content -Path $File.FullName -Value $FileContent2
}
## Transforming the array into a collection
# File path
$Path = 'c:\Path_File'
# Content to add
$TextToAdd = "lang: es"
# List the files
$Files = Get-ChildItem -path $Path -File
# Loop for each file
foreach ( $File in $Files ) {
# Load the contents of the file
$FileContent3 = get-content $File.FullName
# Transformation into a collection to obtain the .Insert() method
$FileContent3 = {$FileContent3}.invoke()
# Add content
# 7 corresponds to an addition to the 8th line
$FileContent3.Insert(7,$TextToAdd)
# Modify the file
Set-Content -Path $File.FullName -Value $FileContent3
}

Related links