How to Append Data to a Text File Using PowerShell

You can use the PowerShell add-content cmdlet to append data to a text file. Here is an example of how to use the add-content PowerShell cmdlet to append text to a file on Windows. We'll also explain the command-line options that you can use.

Powershell add-content example

Step 1. Open PowerShell with elevated privileges.

Step 2. Execute the following command (change the file path):

Add-Content c:\scripts\test.txt "The End"

By default, the data is appended after the last character. If you want to append the data on a new line in the text document, use 'n. Some other special characters can be used with the add-content cmdlet.

Here are some other special characters that can be used with the add-content cmdlet.

  • `0 -- Null
  • `a -- Alert
  • `b -- Backspace
  • `n -- New line
  • `r -- Carriage return
  • `t -- Horizontal tab
  • `' -- Single quote
  • `" -- Double quote

Take a look here if you need to create a directory first.

Frequently Asked Questions

How can I append multiple lines of text to a file using PowerShell?

You can use an array of strings with Add-Content. For example:

Add-Content -Path "C:\example.txt" -Value "Line 1", "Line 2", "Line 3"

Can I append data to a file without overwriting existing content?

Yes, Add-Content appends data without overwriting existing content in the file.

How do I append data to a file in a new line using PowerShell?

By default, Add-Content adds the new data on a new line. If you need to ensure this, you can include a newline character ("`n") in your value.

Is it possible to append data from a variable to a text file?

Yes, you can append data from a variable. For example:

$data = "This is a test"; Add-Content -Path "C:\example.txt" -Value $data

How can I append the output of a PowerShell command to a file?

Use a pipe (|) to direct the output. For example:

Get-Process | Out-String | Add-Content -Path "C:\processes.txt"

Can I append data to a file on a remote computer using PowerShell?

You can use PowerShell remoting with Invoke-Command. Example:

Invoke-Command -ComputerName RemotePC -ScriptBlock { Add-Content -Path "C:\example.txt" -Value "Remote data" }

Is there a way to append data to a file with a specific encoding?

Yes, use the -Encoding parameter. For example:

Add-Content -Path "C:\example.txt" -Value "Some data" -Encoding UTF8

How can I verify that my data was appended successfully?

You can use Get-Content to display the file contents. For example:

Get-Content -Path "C:\example.txt"

Are there any limitations to the size of the data I can append?

PowerShell can handle large files, but performance may degrade with very large files. It's more efficient to work with smaller chunks of data.