How to Append to Text File in PowerShell (With Examples)


Often you may want to append text to the end of a text file using PowerShell.

You can use the following methods to do so:

Method 1: Append One Line to Text File

$my_string | Add-Content $my_file

This particular example will append the string stored in the $my_string variable to the end of the text file specified by the $my_file variable.

Method 2: Append Multiple Lines to Text File

$string1, $string2, $string3 | Add-Content $my_file

This particular example will append the strings stored in the $string1, $string2 and $string3 variables as three new lines at the end of the text file specified by the $my_file variable.

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

Example 1: How to Append One Line to Text File Using PowerShell

Suppose we have a CSV file saved in the following location:

  • c:\users\bobbi\cities.txt

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

This text file contains ten total lines that show the names of various U.S. cities.

Suppose that we would like to add the city name “Boise” at the end of the file.

We can use the following syntax to do so:

$new_city = "Boise"
$new_city | Add-Content $my_file 

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

PowerShell append text to file

When can see that one new line has been appended to the text file that contains “Boise” as the city name, just as we specified in the $new_city variable.

Example 2: How to Append Multiple Lines to Text File Using PowerShell

Suppose that we would like to add the following city names to the end of our text file:

  • Boise
  • Milwaukee
  • Chicago

We can use the following syntax to do so:

$new_city1 = "Boise"
$new_city2 = "Milwaukee"
$new_city3 = "Chicago"

$new_city1, $new_city2, $new_city3 | Add-Content $my_file 

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

PowerShell append multiple lines to text file

When can see that three new lines have been appended to the end of the text file, which contain the names of the three cities that we specified in the string variables.

Note: You can find the complete documentation for the Add-Content cmdlet 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