Bagikan melalui


Using the Add-Content Cmdlet

Appending Data to a Text File

One use of the Add-Content cmdlet is to append data to a text file. For example, this command adds the words “The End” to the file C:\Scripts\Test.txt:

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

By default Add-Content tacks the new value immediately after the last character in the text file. If you’d prefer to have The End listed on a separate line, then simply insert `n (Windows PowerShell lingo for “new line”) into the value being written to the file. In other words:

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

Seeing as how you asked, here are some of the other special characters that can be used in Windows PowerShell output:

  • `0 -- Null

  • `a -- Alert

  • `b -- Backspace

  • `n -- New line

  • `r -- Carriage return

  • `t -- Horizontal tab

  • `' -- Single quote

  • `" -- Double quote

Keep in mind that some of these characters are intended for use only from the Windows PowerShell prompt. For example, the special character `a causes your computer to beep. Don’t believe us? Try this command and see what happens:

Write-Host `a

One nice feature of Add-Content is the fact that it accepts wildcard characters. For example, suppose you want to add a timestamp to the end of all the .log files in the C:\Scripts folder. This command will do just that:

$A = Get-Date; Add-Content c:\scripts\*.log $A

As you can see, here we’re simply assigning the current date and time to a variable named $A, then appending the value of that variable to all of the .log files in C:\Scripts.

Add-Content Aliases
  • ac