22

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.

So:

"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?

BSAFH
  • 725
  • 3
  • 6
  • 19
  • 1
    `Out-File` defaults to unicode encoding by default. Use `-Encoding Ascii`. In your case `out-file -Encoding Ascii -append textfile.txt`. Add-Content uses ascii by default and also appends by default. `"This is a test" | Add-Content textfile.txt`. You did not send a newline so it will not write one to file. – Matt Dec 11 '14 at 00:22
  • possible duplicate of [NUL-byte between every other character in output](http://stackoverflow.com/questions/11147179/nul-byte-between-every-other-character-in-output) – Matt Dec 11 '14 at 00:25
  • @Matt You should have just made your first comment an answer and considered the issue resolved. – TheMadTechnician Dec 11 '14 at 00:27
  • @TheMadTechnician Never sure if it is worth answering duplicate questions – Matt Dec 11 '14 at 00:29
  • 3
    @Matt If it's worded differently enough I think it helps more people find answers since everyone searches differently. – Booga Roo Dec 11 '14 at 23:05
  • Truly works, here my example: { Test-NetConnection -ComputerName xxx.xx.xxx.com -CommonTCPPort HTTP | Out-File -append httpportscan.txt } – apl Jul 14 '21 at 15:18

2 Answers2

39

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.

Matt
  • 45,022
  • 8
  • 78
  • 119
0

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Nando
  • 102
  • 5