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 5 6 7 321
  1. May 18th, 2020 at 03:46 | #1
  2. May 18th, 2020 at 12:27 | #2
  3. May 23rd, 2020 at 02:22 | #3
  4. May 23rd, 2020 at 03:34 | #4
  5. May 23rd, 2020 at 03:38 | #5
  6. May 23rd, 2020 at 03:42 | #6
  7. May 23rd, 2020 at 04:05 | #7
  8. May 23rd, 2020 at 04:21 | #8
  9. May 23rd, 2020 at 05:21 | #9
  10. May 24th, 2020 at 19:48 | #10
  11. May 25th, 2020 at 02:47 | #11
  12. May 25th, 2020 at 21:49 | #12
  13. May 26th, 2020 at 21:16 | #13
  14. May 26th, 2020 at 21:21 | #14
  15. May 26th, 2020 at 21:25 | #15
  16. May 26th, 2020 at 21:43 | #16
  17. May 26th, 2020 at 22:54 | #17
  18. May 26th, 2020 at 23:46 | #18
  19. May 27th, 2020 at 14:10 | #19
  20. May 28th, 2020 at 07:42 | #20
  21. May 28th, 2020 at 20:29 | #21
  22. June 4th, 2020 at 21:50 | #22
  23. June 4th, 2020 at 22:05 | #23
  24. June 4th, 2020 at 22:18 | #24
  25. June 4th, 2020 at 22:31 | #25
  26. June 4th, 2020 at 22:39 | #26
  27. June 4th, 2020 at 22:41 | #27
  28. June 4th, 2020 at 23:04 | #28
  29. June 4th, 2020 at 23:04 | #29
  30. June 4th, 2020 at 23:10 | #30
  31. June 4th, 2020 at 23:36 | #31
  32. June 4th, 2020 at 23:56 | #32
  33. June 5th, 2020 at 00:02 | #33
  34. June 5th, 2020 at 00:47 | #34
You must be logged in to post a comment.