How do I prevent PowerShell's Out-File command from appending a newline after the text it outputs?
For example, running the following command produces a file with contents "TestTest\r\n" rather than just "TestTest".
"TestTest" | Out-File -encoding ascii test.txt
To send a PowerShell command's output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet. Out-File saves data to a file but it does not produce any output objects to the pipeline.
There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.
Using PowerShell newline in Command To add newline in the PowerShell script command, use the` (backtick) character at the end of each line to break the command into multiple lines.
The first method of printing output is using the Write-Output cmdlet. This cmdlet is used to pass objects in the pipeline to the successive commands. In case of the command being last, the final object is written to the console. To pass on error objects, Write-Error cmdlet is used.
In PowerShell 5.0+, you would use:
"TestTest" | Out-File -encoding ascii test.txt -NoNewline
But in earlier versions you simply can't with that cmdlet.
Try this:
[System.IO.File]::WriteAllText($FilePath,"TestTest",[System.Text.Encoding]::ASCII)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With