In this post, we are going to see how to append some text to a file. We will add text without deleting old content. This is very useful for creating system logs in PowerShell. There are several different ways in which we can write the content to a file and appending the content is very important. For appending the content, we will use the Add-Content commandlet.
- PowerShell Append text to file.
- PowerShell creates and add content to a file.
- Add content to a read-only file.
- Add-content alias
- Flags in Add-Content.
- Append file using redirection PowerShell.
People Also Search For:
PowerShell Append text to file:
The add-content will append the content to the file. Here is a basic example.
The above script will create a file called teckangaroo.com and we will add one word hello. We will close the file and continue with the following script.
This script will add another word to the file without deleting the original content. We will view the content and check.
The output of the file is shown below. Clearly, this appends the text of the file without deleting the contents.
PowerShell create and add content to a file:
We can add the contents from an existing file to a new file by creating it. The following script will create a new file and copy the contents to the new file and open it.
The above script will have the following output.
PowerShell add content to a read-only file:
We can use the -force switch to add content to even read-only files. Consider a file that is read-only named readonlyfile.txt. We can add content to the file with the help of -force switch as shown below.
PowerShell appends content alias:
The add-content as an alias called ac. This can be used as shown below to append content to an existing file.
PowerShell add-content flags:
Apart from the above examples, we can do other useful things using the add-content with the help of different flags.
Please note that we have to use the above commands wrapped inside quotes.
PowerShell appends to file using file redirection:
This is perhaps the easiest syntax to append content to the file. This involves only the redirection stream syntax as shown below.
The above script will append the contents to the file teckangaroo.com
In this post, we learned how to append text to file using PowerShell. We use the add-content commandlet for this purpose. There is another easy way to append text to a file using the redirect to file syntax.
If you want to know more about a redirect to file, stay tuned to TecKangaroo.