Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 271
BSAFH Avatar asked Dec 11 '14 00:12

BSAFH


People also ask

How do you split a string by a new line in PowerShell?

PowerShell string Split() function splits the string into multiple substrings based on the specified separator. To split on newline in a string, you can use the Split() method with [Environment::Newline].

What does out string do in PowerShell?

The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.

How do you break a line in PowerShell?

Use `N to Break Lines in PowerShell You can use the new line `n character to break lines in PowerShell. The line break or new line is added after the `n character.

What is the new line character in PowerShell?

`n is used in Powershell to append a new line to the standard output. The use of `n in Powershell is similar to \n in C++ or Java. The backtick character (`) represents an escape character in Powershell.


1 Answers

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.

like image 101
Matt Avatar answered Nov 02 '22 23:11

Matt