Home > PowerShell > Append Text to a File Using Add-Content in PowerShell

Append Text to a File Using Add-Content in PowerShell

Here’s a quick tutorial on how to add text to the end of a text file using the Add-Content or its alias ac in PowerShell. In this first example let’s add "This is the last line" to the end of a file.

1
Add-Content c:\sample.txt "This is the last line"

The example above adds the text to the last line, it doesn’t actually create a new line, so let’s try it again, and make sure that this time the text that we concatenate is on the last line all by itself.

1
Add-Content c:\sample.txt "`r`nThis is the last line"

You’ll notice a `r`n this is an escape character to tell PowerShell to add a carriage return and a new line, you’ll need this when working with Windows file. If your going to move this file to a unix or linux computer, you’ll only need a `n there’s no need for the carriage return.

Here is a list of escape characters:

  • `0 — Null
  • `a — Alert
  • `b — Backspace
  • `n — New line
  • `r — Carriage return
  • `t — Horizontal tab
  • `’ — Single quote
  • `” — Double quote

The example I gave above was the quick and dirty, we should really explicitly state our arguments and use quotes around the path, to do that we will add a path and a value argument

1
Add-Content -Path "c:\sample.txt" -Value "`r`nThis is the last line"

Here’s a useful example, suppose you want to map hostname to a particular IP address. Let’s map example.com to point to 127.0.0.1, we’ll do this using the ac alias for Add-Content.

1
ac -Path "C:\WINDOWS\system32\drivers\etc\hosts" -Value "`r`n127.0.0.1    example.com"
  1. No comments yet.
Comment pages
1 2 3 4 321
  1. March 6th, 2020 at 22:09 | #1
  2. March 8th, 2020 at 00:18 | #2
  3. March 8th, 2020 at 02:11 | #3
  4. March 8th, 2020 at 04:14 | #4
  5. March 8th, 2020 at 15:26 | #5
  6. March 8th, 2020 at 23:34 | #6
  7. March 9th, 2020 at 03:44 | #7
  8. March 11th, 2020 at 00:32 | #8
  9. March 13th, 2020 at 06:20 | #9
  10. March 14th, 2020 at 09:44 | #10
  11. March 16th, 2020 at 19:30 | #11
  12. March 21st, 2020 at 03:40 | #12
  13. March 21st, 2020 at 04:00 | #13
  14. March 21st, 2020 at 04:06 | #14
  15. March 24th, 2020 at 03:11 | #15
  16. March 24th, 2020 at 07:13 | #16
  17. March 25th, 2020 at 07:25 | #17
  18. March 25th, 2020 at 13:48 | #18
  19. March 26th, 2020 at 00:40 | #19
  20. March 26th, 2020 at 04:07 | #20
You must be logged in to post a comment.