Search code examples
powershellnewlinecarriage-returnpowershell-cmdlet

Out-File and carriage returns


If I have a program, for example this Go program:

package main
import "fmt"

func main() {
   fmt.Print("North East\n")
   fmt.Print("South West\n")
}

This program produces no carriage returns at all, only newlines. However if I do this:

prog.exe > prog.txt

PowerShell takes it upon itself to add carriage returns to every line. I only want PowerShell to faithfully output what my program created, nothing more. So I tried this instead:

prog.exe | Out-File -NoNewline prog.txt

and PowerShell didn't add carriage returns, but it went ahead and removed the newlines too. How do I do what I am trying to do? Update: based on an answer, this seems to do it:

start -rso prog.txt prog.exe

Solution

  • It seems this is due to the behavior of redirecting output. It's split up into separate lines wherever a newline is detected, but when Powershell joins the lines again, it will use both newline and carriage return (the Windows default).

    This should not be an issue though, if you redirect the output directly. So this should give you the expected behavior:

    Start-Process prog.exe -RedirectStandardOutput prog.txt