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

孤者浪人 提交于 2019-12-22 04:06:27

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/27413264/out-file-append-in-powershell-does-not-produce-a-new-line-and-breaks-string-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!