PowerShell: How to Add Text to Each Line in a File


You can use the following syntax in PowerShell to add text to each line in a file:

Get-Content cities.txt | ForEach { $_ + "_City" }

This particular example will add the string “_City” to the end of each line in the file named cities.txt.

Here is what the various commands do:

  • Get-Content: Returns all lines from the text file
  • ForEach: Specifies an action to perform on each line of the file
  • $_: Returns the existing text from current line
  • +: Specifies text to concatenate to the end of existing line

The following example shows how to use this syntax in practice.

Example: How to Add Text to Each Line in a File Using PowerShell

Suppose we have a file named cities.txt in our current directory that contains the names of various U.S. cities.

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to add the text “_City” to the end of each line in the file.

We can use the following syntax to do so:

Get-Content cities.txt | ForEach { $_ + "_City" }

The following screenshot shows how to use this syntax in practice:

PowerShell add text to each line of file

Notice that the text “_City” has been added to the end of each line in the file, just as we specified.

Note that we could also use the following syntax to instead add text to the beginning of each line in the file:

Get-Content cities.txt | ForEach { "City_" + $_ }

The following screenshot shows how to use this syntax in practice:

PowerShell add text to beginning of each line in file

Notice that the text “City_” has been added to the beginning of each line in the file.

Note: You can find the complete documentation for the Foreach statement in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Export-Csv with Append
PowerShell: How to Use Export-Csv with No Headers
PowerShell: How to Count Number of Lines in File

Leave a Reply