iTayb
iTayb

Reputation: 12743

How use write to stdout without a newline?

When using the Write-Output command, a new line is automatically appended. How can I write strings to stdout (the standard output) without a newline?

For example:

powershell -command "write-output A; write-output B"

Outputs:

A
B

(Write-Host is no good - it writes data to the console itself, not to the stdout stream)

Upvotes: 2

Views: 3030

Answers (3)

Matt
Matt

Reputation: 46730

mjolinor/famousgarkin explain why the output has a new line that is not itself generated by Write-Output. Simple approach to deal with this is to build your output string with Write-Output

$text = ("This","is","some","words") -join " "; 
$string = Write-Output $text
$string += Write-Output $text
$string

Output

This is some wordsThis is some words

Upvotes: 0

famousgarkin
famousgarkin

Reputation: 14126

Write-Output writes objects down the pipeline, not text as in *nix for example. It doesn't do any kind of text formatting such as appending newlines, hence no need for newline handling options. I see people very often not coming to grips with this.

If you are referring to the newlines printed on the console output, it's because the pipeline is always eventually terminated by Out-Default, which forwards to a default output target (usually Out-Host), which in turn, if it doesn't receive a formatted input, runs the objects through an appropriate default formatter (usually Format-List or Format-Table). The formatter here is the only one in the process responsible for formatting the output, e.g. printing each object on a new line for the console output.

You can override this default behavior by specifying the formatter of your liking at the end of the pipeline, including your own using Format-Custom.

Upvotes: 3

mjolinor
mjolinor

Reputation: 68341

Write-Output is not appending the newlines.

Try this:

filter intchar {[int[]][char[]]$_}

'123' | Write-Output | intchar

49
50
51

The filter is converting the string to the ASCII int representation of each character. There is no newline being appended.

Adding a couple of explicit newlines for comparison:

"1`n2`n3" | write-output | intchar

49
10
50
10
51

Now we see the additional newlines between the characters, but still no newline appended to the string.

Not sure what your application is, but if you're getting unwanted newlines in your output, I don't think it's Write-Output that's doing it.

Upvotes: 2

Related Questions