Powershell – Out-File -append in Powershell does not produce a new line and breaks string into characters


I'm trying to understand some weird behaviour with this cmdlet.

If I use "Out-File -append Filename.txt" on a text file that I created and entered text into via the windows context menu, the string will append to the last line in that file as a series of space separated characters.


"This is a test" | out-file -append textfile.txt

Will produce:
T h i s i s a t e s t

This wont happen if out-file creates the file, or if the text file has no text in it prior to appending. Why does this happen?

I will also note that repeating the command will just append in the same way to the same line. I guess it doesn't recognise newline or line break terminator or something due to changed encoding?

Best Solution

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

Related Question