Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent trailing newline in PowerShell Out-File command

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 
like image 318
Matt Avatar asked Feb 08 '16 21:02

Matt


People also ask

How do I pipe a PowerShell output to a text File?

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.

How do I redirect output in PowerShell?

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.

How do you end a line in PowerShell?

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.

How do I get output in PowerShell?

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.


1 Answers

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) 
like image 81
briantist Avatar answered Sep 22 '22 20:09

briantist