Powershell: Add -NoNewLine switch parameter to Write-Output cmdlet

Created on 6 May 2019  路  3Comments  路  Source: PowerShell/PowerShell

As a user I want to do the following:

$output = [System.IO.StreamReader]$stream.ReadToEnd()
Write-Output -InputObject $output -NoNewLine

The -NoNewLine parameter is required to prevent an extra new line from being inserted at the end of the output.

Area-Cmdlets-Utility Issue-Enhancement Resolution-Answered

Most helpful comment

Write-Output (unlike Write-Host) is not concerned with output formatting / presentation, so adding -NoNewLine isn't appropriate.

Write-Output writes objects to the success output stream.

If such an object is a (multi-line) string that should have no trailing newline, use a string operation to trim that newline; e.g.:

# Create a file with a trailing newline.
@'
a
b
'@ > t.txt

# Read the file in full, as-is.
$content = [io.file]::ReadAllText("$pwd/t.txt")

# Strip the trailing newline, if any.
$content -replace '\r?\n\z'

If, by contrast, you want to create output _for display_ and output a string in a manner that makes _subsequent console output_ start immediately after rather than on a new line, use Write-Host -NoNewline.

All 3 comments

@mklement0 Make sense to add this to #5108?

Write-Output (unlike Write-Host) is not concerned with output formatting / presentation, so adding -NoNewLine isn't appropriate.

Write-Output writes objects to the success output stream.

If such an object is a (multi-line) string that should have no trailing newline, use a string operation to trim that newline; e.g.:

# Create a file with a trailing newline.
@'
a
b
'@ > t.txt

# Read the file in full, as-is.
$content = [io.file]::ReadAllText("$pwd/t.txt")

# Strip the trailing newline, if any.
$content -replace '\r?\n\z'

If, by contrast, you want to create output _for display_ and output a string in a manner that makes _subsequent console output_ start immediately after rather than on a new line, use Write-Host -NoNewline.

Closed as invalid.

Was this page helpful?
0 / 5 - 0 ratings