PowerShell Writing Files
Writing files is saving text from a script into a file on disk. Set-Content creates or replaces a file, and Add-Content adds lines to the end of a file.
Set-Content replaces a file
The second write replaces the first. Only the newest text is left in the file.
Set-Content -Path "note.txt" -Value "first"
Set-Content -Path "note.txt" -Value "second"
Get-Content -Path "note.txt"Add-Content appends lines
Add-Content keeps the old lines and adds new ones at the end. The file then holds both lines.
Set-Content -Path "note.txt" -Value "one"
Add-Content -Path "note.txt" -Value "two"
Get-Content -Path "note.txt"A written file ends with a newline
The word apple is 5 letters long. The file is 6 bytes because Set-Content adds a newline at the end.
Set-Content -Path "a.txt" -Value "apple"
(Get-Item -Path "a.txt").LengthExample
Set-Content -Path "shopping.txt" -Value @("milk", "bread")
Add-Content -Path "shopping.txt" -Value "eggs"
Get-Content -Path "shopping.txt"Key points
- Set-Content writes text into a file and replaces any text already there.
- Add-Content adds new lines to the end of an existing file.
- Set-Content can write a list, and each item becomes one line in the file.
- Read a file back with Get-Content to check what was written.
In this example, Set-Content writes two lines into a new file. Add-Content then adds a third line at the end. Get-Content reads the file back and prints all three lines in order.
Note
Set-Content adds a newline at the end of the file, so the file is one byte longer than the text alone.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A file already holds the line one. What does the file hold after Add-Content -Path "note.txt" -Value "two"?