Skip to content

Out-String should not append a trailing newline #14444

Closed

Description

Summary of the new feature/enhancement

It should be possible to use Out-String in a manner that doesn't append a trailing newline, which is what it currently does and has always done.

Note that -NoNewLine is not a solution, because it suppresses all newlines, so that two or more output lines are then simply directly concatenated (like -join ''; e.g. 1, 2 | Out-String -NoNewLine yields 12).

Here's a demonstration of the problem:

# CURRENT behavior:
PS> ('foo' | Out-String) -replace '\r?\n', '<newline>'
foo<newline>   #  A newline was appended.

I see two options:

Activity

  1. added
    Issue-Enhancement
    on Dec 16, 2020
  2. bpayette commented on Dec 17, 2020

    @bpayette
    Contributor

    Out-String formats an object for presentation as a string. It should add a new line because that's how formatting works. Given that, I don't understand what the problem is - can you clarify? Thanks.

  3. mklement0 commented on Dec 18, 2020

    @mklement0
    ContributorAuthor

    It should add a new line

    I don't think it should. Why do you think so?

    I would expect:

    Get-Date

    and

    Get-Date | Out-String

    to produce the same output, yet they don't (the latter has an extra newline).

    Given that piping to Out-String is a convenient way to capture stdout from an external program in a single string - and remember that strings are out-of-band objects with respect to formatting and are passed through - it is inconvenient to have a trailing newline in the resulting string with respect to further programmatic processing.

    In other words:

    PS> $out = cmd /c 'echo a&echo b' | Out-String

    should be equivalent to:

    PS>  $out = (cmd /c 'echo a&echo b') -join [Environment]::NewLine

    yet it isn't, due to the trailing newline.

    In short: there's no good reason to append a newline to the (formatted representation) of the last input object.

  4. bpayette commented on Dec 19, 2020

    @bpayette
    Contributor

    there's no good reason to append a newline to the (formatted representation) of the last input object.

    The purpose of Out-String is to render objects as presentable text which includes trailing newlines. If what you actually want to do is join a bunch of strings then use -join because that's it for.

  5. mklement0 commented on Dec 19, 2020

    @mklement0
    ContributorAuthor

    Yes, -join is a workaround, but that still doesn't justify the trailing newline:

    • If you output the string resulting from Out-String, it is the standard output formatting that will add the trailing newline for you - just like sending the output to a file will do that for you - just like interactively outputting 'foo' prints a newline before the next prompt is displayed.

    • If you programmatically process Out-String output, the trailing newline is an unnecessary nuisance.

    Each formatted output individually may or may not have trailing newlines (e.g., Get-Date vs. 'foo').

    Newlines are only needed as separators between multiple formatted representations, not as a terminators.

    Again - there's no justification for Get-Date and Get-Date | Out-String to produce different output (which they do, due to the trailing newline) - both in the console and if you redirect to a file - and there's no reason why
    ((cmd /c 'echo a & echo b' | Out-String) -split [Environment]::NewLine).Count should report 3 rather than 2, given that there are only two output lines.

  6. ExE-Boss commented on Jan 15, 2021

    @ExE-Boss

    As I said in #13071 (comment):

    This is the expected behaviour, because both Out‑String and Set‑Content add a trailing newline by default.


    You can use the ‑NoNewline switch with Set‑Content to disable adding the extra trailing newline:

    @(
    	\"$($PSStyle.Foreground.Blue)Hello$($PSStyle.Reset)\",
    	'string2'
    ) `
    	| Out-String `
    	| Set-Content -Path test2.txt -NoNewline
  7. mklement0 commented on Jan 15, 2021

    @mklement0
    ContributorAuthor

    ExE Boss (@ExE-Boss): Out-String is an in-memory operation, whereas Set-Content is a file operation.

    When you use Out-String, you typically want to process the result in memory - otherwise, you'd just use > / Out-File directly.

    For in-memory processing, it is reasonable for multiple formatted representations to be joined with a separator (a newline), and not for each representation to have a terminator, which is a concept that applies to (line-oriented text) files, especially on Unix.

    If Out-String behaved that way, you could later use it with Set-Content as-is, without having to resort to the -NoNewline workaround.

  8. kilasuit commented on Jan 15, 2021

    @kilasuit
    Collaborator

    Isn't the crux of this that in interactive output in the terminal shows a trailing new line and when run in a script (where there often isn't an interactive session) it shouldn't?

    If so then that can be checked within the cmdlet whether or not the session is in non-interactive mode or not & I don't believe would be a breaking change

  9. mklement0 commented on Jan 15, 2021

    @mklement0
    ContributorAuthor

    Ryan Yates (@kilasuit), this is primarily about the trailing newline being unhelpful in programmatic processing of Out-String output.

    As for the display side of things:

    Both default host output and file-creation cmdlets (Out-File / >, Set-Content) are clearly designed not to expect the data to already have a trailing newline, and therefore blindly append one (by default).
    (And I don't see how interactive vs. script processing figures into this, but perhaps you can elaborate.)

    Given that Out-String currently itself appends a trailing newline to the resulting in-memory string, you end up having to fight that design:

    • If you later split the string into lines, you'll end up with an extra empty array element at the end (("foo`nbar`n" -split '\n').Count is 3).

    • On printing to the host / saving to a file, you must then suppress the extra trailing newline:

      • With -NoNewLine, if you use Out-File / Set-Content (> is then not an option)
      • For to-host output you're stuck with something awkward like Write-Host -NoNewline (Get-Date | Out-String)

    Of course, you can avoid the empty array element / the need for these workarounds by stripping the trailing newline manually first - ((Get-Date | Out-String) -replace '\n\z') - but the whole point of this issue is that the trailing newline shouldn't be added to the in-memory data (string) to begin with: there is no upside to doing so, only downsides.

  10. ExE-Boss commented on Jan 15, 2021

    @ExE-Boss

    Out‑String also supports ‑NoNewline.

  11. mklement0 commented on Jan 15, 2021

    @mklement0
    ContributorAuthor

    ExE Boss (@ExE-Boss), to quote from the OP:

    Note that -NoNewLine is not a solution, because it suppresses all newlines, so that two or more output lines are then simply directly concatenated (like -join '').

    For instance:

    PS> 1, 2 | Out-String -NoNewline
    12

    See also: #5108

  12. jazzdelightsme commented on Jan 16, 2021

    @jazzdelightsme
    Contributor

    I think maybe mklement0 chose Get-Date as an example because it produces a simple object that isn't a string (a DateTime), so that Out-String would be doing "some work" to convert something to a string.

    But consider even just a plain string!

    'asdf'

    versus

    'asdf' | Out-String

    How would one could consider that 'asdf' is not "rendered as presentable text"? In other words, who would consider the output of the latter to be "presentable text", but not the former?

    Adding newlines in is ONLY interesting where there are multiple input objects: newlines in that case are used to separate them (unless belayed by -NoNewline). The current last (trailing) newline is separating the last object from ... what? It serves no purpose; it is not separating it from anything. We should get rid of it.

    Consider also this pathological scenario:

    'asdf' | Out-String | Out-String | Out-String | Out-String | Out-String 

    Let's stop the madness and pull this burr out from under the saddle.

    (edit: I called that last scenario "pathological", because nobody is going to pipe through a long chain of Out-String commands, but I think the nerve it hits is quite reasonable: it feels like it ought to be idempotent)

  13. 17 remaining items

  14. ghost closed this as completedon Mar 17, 2023
  15. jhoneill commented on Mar 17, 2023

    @jhoneill

    The Cmdlet working group has reviewed this issue. We have decided changing the default behavior would break way too many things. Work rounds for things that don't like trailing line breaks have be around for a long time. Resolved as by design.

    A new switch to strip the trailing new line wouldn't break anything, and is a suggested resolution in the OP.

    The issue is more complicated than posed in the OP. (1) Formatting has never been consistent. A date gets leading and trailing line breaks (because it has formatting rules) but numbers and strings (with no formatting rules don't)

    #613 [——€] PS7 ~\Documents\PowerShell> 1,2
    1
    2
    #614 [——€] PS7 ~\Documents\PowerShell> $d=get-date; $d, $d.AddDays(1)
    
    17 March 2023 10:40:47
    18 March 2023 10:40:47
    
    #615 [——€] PS7 ~\Documents\PowerShell>
    

    (2) if you run something like Get-Date | format-table | out-file delete.me How many leading and trailing carriage returns do we expect in the file, and what should be done to ensure they are added or not ? To be consistent a lot of other commands would need specifiers for no leading break ($d, $d.AddDays(1) > delete.me produces file which starts with a blank line) as well as no trailing break or only single final break etc. Yes, in isolation $String1 | out-string | out-string | out-string adding a line break every time looks daft. But it is how $string1 > delete.me followed by $string2 >> delete.me avoids mashing lines together.

    (3) We have had the present formatting with accepted inconsistencies for a long time. We know that whatever it does by default will not work in every case. Work rounds are understood and some people will have functions which take a string from Out-string and reformat it for their use case. Adding a switch to support an exception works for the person bothered by that exception. Speaking for myself, I'd like out-string to be culture aware so I could do get-date | out-string -culture fr-fr because using local culture is sometimes wrong. If every exceptional case was given a switch it would be never-ending. And of course, old scripts would work with the new version but as soon as someone takes a script which uses the new switch and tries to run it on a server where only Windows PowerShell exists things break, and there is a quite a high bar set for doing that.

    My hunch is questions in this area will continue to be asked, and the door is not nailed shut on this, but hopefully that explains why for this case, now, the answer is no.

  16. mklement0 commented on Mar 17, 2023

    @mklement0
    ContributorAuthor

    A new switch to strip the trailing new line wouldn't break anything, and is a suggested resolution in the OP.

    Good point, @ImportTaste. I hope that

    (which covers multiple cmdlets, not just Out-String) will now be considered for implementation.

  17. mklement0 commented on Mar 17, 2023

    @mklement0
    ContributorAuthor

    The issue is more complicated than posed in the OP.

    The quirks and complexities of the formatting system are a red herring with respect to what this issue asked for.

    It is a simple as it gets:

    Switch from:

    (<whatever-lines-the-formatting-system-generates> -join [Environment]::NewLine) + [Environment]::NewLine

    to just:

    <whatever-lines-the-formatting-system-generates> -join [Environment]::NewLine

    That extra newline was never justified - but whether or not it is present doesn't matter if you use Out-String for actual (complex) object formatting (say, Get-ChildItem output), because there you decidedly get a for-display-only representation whose specifics you shouldn't rely on for programmatic processing.

    If you conceive of Out-String as cmdlet solely for emitting for-display representations - and it certainly primarily is - then changing its output would not be a backward-compatibility concern, because for-display representations aren't part of the backward-compatibility contract.

    In (widespread) practice, however, Out-String is also used to emit data, such as in calls to native (external) programs, as a convenient way of getting an external program's output as a single, multiline string (instead of the line-by-line streaming that happens by default).

    Given that external-program output is only ever interpreted as strings, and strings render as-is (in formatting-system speak, they render out of band), Out-String output - which then amounts to:

    (<lines-from-external-program> -join [Environment]::NewLine) + [Environment]::NewLine

    is suitable for programmatic processing - but in that case the trailing newline is decidedly a nuisance:

    • If you split the string into lines later (-split '\r?\n'), you'll get an extra, empty array element.

    • If you send it to Out-File or Set-Content later, you'll get an extra empty line.

  18. CyberBorga commented on Mar 17, 2023

    @CyberBorga

    I love Powershell, but as a long time Linux bash user, I agree with Michael Klement (@mklement0). I'd prefer if the Out-String cmdlet did NOT add a trailing newline character (i.e., if I wanted a newline, I would have told you to add one, or I would have added one myself!).

    However, since Powershell commands work with objects (vs. bash commands which usually work with text), a possible answer lies in Powershell's object-oriented inheritance. Since all objects inherit their methods and properties from their parents, I would recommend using the ToString method available to all .NET/Powershell objects.

    In the example above, you can use ToString to convert the pipeline to strings vs. using the Out-String cmdlet:

    1, 2 | % { $_.ToString()}

    This should produce the results you wanted:

    PS C:\Users\cyberborga> 1, 2 | % { $_.ToString()}
    1
    2
    PS C:\Users\cyberborga>
    

    Of course, since child objects can override the ToString method, your results may be unpredictable for more complex objects, such as the System.DateTime object returned by Get-Date, which prints the date/time in "the current culture's short date and long time pattern".

    PS C:\Users\cyberborga> Get-Date  | % { $_.ToString()}
    3/17/2023 9:42:31 AM
    PS C:\Users\cyberborga>
    

    In these cases, I think the easiest answer is just to ask the cmdlet to output the results in a format you would like (vs. using the IFormatProvider options).

    In the example above, you could use:

    PS C:\Users\cyberborga> Get-Date -Format "dddd, MMMM, d, yyyy hh:mm:ss tt"
    Friday, March, 17, 2023 09:54:07 AM
    PS C:\Users\cyberborga>
    
    • NOTE: You don't need to convert the results of this command to a string, because the Get-Date cmdlet outputted a string.

    I hope this helps.

  19. CyberBorga commented on Mar 17, 2023

    @CyberBorga

    Of course, an even easy answer might be to just use the Out-String -Stream option, which would preserve the "normal" output of cmdlets (i.e., Get-Date wouldn't require any extra formatting to get the normal 1> outputs):

    PS C:\Users\cyberborga> Get-Date
    
    Friday, March 17, 2023 10:12:46 AM
    
    
    PS C:\Users\cyberborga> Get-Date | Out-String -Stream
    
    Friday, March 17, 2023 10:12:55 AM
    
    
    PS C:\Users\cyberborga> 1,2 | Out-String -Stream
    1
    2
    PS C:\Users\cyberborga>
    

    Good luck.

  20. jhoneill commented on Mar 17, 2023

    @jhoneill

    CyberBorga however -stream outputs as many strings as there are objects, so to they may need to be joined together.

  21. mklement0 commented on Mar 17, 2023

    @mklement0
    ContributorAuthor

    CyberBorga, to flesh out James O'Neill (@jhoneill)'s comment:

    • External-program output implicitly behaves like Out-String -Stream: that is, stdout is broken into lines (of what is invariably treated as string output) and each line is streamed to the pipeline as it becomes available. Therefore,
      & $someExternalCli … | % ToString and
      & $someExternalCli … | Out-String -Stream (note that there's also a built-in oss function that wraps Out-String -Stream) are in effect expensive no-ops, because they behave the same as just
      & $someExternalCli …

    • The use case that this proposal targets is Out-String's default behavior of emitting a single, multiline string rather than a stream of lines (which in turn turns into an array of strings when captured).

    • As such, the workaround is (& $someExternalCli …) -join [Environment]::NewLine - not terrible, but less obvious, more complex, and less PowerShell-idiomatic than & $someExternalCli … | Out-String

  22. TheOnlyWei commented on Jun 10, 2023

    @TheOnlyWei

    The Cmdlewt working group has reviewed this issue. We have decided changing the default behavior would break way too many things. Work rounds for things that don't like trailing line breaks have be around for a long time. Resolved as by design.

    Thomas Lee (@doctordns) Resolution by design should be for cases when the design is sound, which in this case, I don't think it is good design to modify user string. A "string" does not mean "a bunch of characters that must end with a newline character". It wouldn't be an issue if the function was named "Out-StringWithNewline". This caveat will continue cost dev time for users because of the surprise newline appended to the end.

    From Microsofts own Docs:
    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/out-string?view=powershell-7.3

    Outputs input objects as a string.

    A string does not need to have a newline at the end.

    I do hope this serves at least as some kind of lesson when it comes to designing commands, that you should not be adding anything to user input at all for commands named like Out-String going forward.

  23. jhoneill commented on Jun 11, 2023

    @jhoneill

    Wei Shi (@TheOnlyWei)

    The job Out-String was designed to do is to output the formatted text for... which includes.

    1. producing formatted strings from the format objects output by format-* commands to writable text printing or writing into a file. So you can do $Table = get-process P* | format-table -autosize ;
      and then $table | Out-String -width 240 > textfile ; or $table | out-String -width 60
    2. Detecting objects which should be formatted with format-* and producing the objects for (1) ...

    Single new-lines, and double new lines are printed based on what seemed like a good idea at the time to the original designers, and that has become 'established custom and practice' meaning changing them would please some people and break code which sees 'custom and practice' as an absolute guarantee of behaviour.

    $x | Out-String is emphatically not the same as [string]$x or $x.tostring()

    for example

    PS> $x = 'a', 'b', 'c'
    PS> $x.ToString()
    System.Object[]
    PS> [string]$x
    a b c
    PS> $x | Out-String
    a
    b
    c
    
    PS> $x -join [System.Environment]::NewLine
    a
    b
    c
    PS>
    

    None of those is right on all occasions.

    A "string" does not mean "a bunch of characters that must end with a newline character".

    Indeed. String is any bunch of characters. We do have zero terminated strings, but .NET strings aren't. The "formatted output for" probably ends with a new line, but might end with more than one...

    It wouldn't be an issue if the function was named "Out-StringWithNewline".

    'String' in the name should be read as "String formatted for printing as is". Picking Out-FormattedString as the name all those years ago might have saved confusion :-) But the String for 1234 and the string formatted for printing 1234 are different meaning that
    1234 | out-string | format-hex
    and
    (1234).tostring() | format-hex
    Show different things.

    This caveat will continue cost dev time for users because of the surprise newline appended to the end.

    Yes. As long as people do not understand that Out-String is making a formatted print-ready version and is distinct from "the string representation of" time will be lost.
    I've shown three ways to make an array into a single string, all valid, and all three are potentially surprising.
    How confident is a reasonably experienced user certain what "my array is $x " and "my array is {0} " -f $x will do?
    If $d is a date does that user know when "The date is " + $d is different from "The date is " + $d.ToString() ?
    (The former does a culture invariant cast, but ToString is culture aware). As a non-American I HATE that.

    Any ways of helping people understand and get to the version they want more quickly will be gratefully received.
    But could we avoid arguments about 15 year old decisions on formatting, please?. The empirical evidence is they has been sufficiently OK, for enough of people, enough of the time, and a different decision would probably have roughly as good/bad, annoying a different set of people on different occasions. I accept that I'll never see a change to make dates culture aware where I think they should be 'it has always been that way' is the worst reason, and yet the change I'd like would break things which rely on established practice. With 15 years of PowerShell behind me I still get surprised by date behaviour so I have some sympathy for anyone who says "There are three ways to convert to string and none is what I want/expect this operation to do!".

    There is a discussion point about whether "Produce the formatted print-ready version BUT WITHOUT THE TRAILING LINE BREAK" is a such a desirable scenario that it should be incorporated into Out-String. The review that happened said no, as I said above that could be revisited. People do believe passionately that decisions made long ago weren't OK, but sometimes that yields arguments which should be left for student moots, or debating societies. Arguing that naming the cmdlet out-string leads to wrong expectations of what it does, or that some formatting it does isn't optimal both fall into that category - at least in my view. On the other hand saying "I'd really benefit from the a -NoTrailingNewLine switch because... " can help us to see things that should be reconsidered (and also applies when if the old decision was perfect).

  24. JDawgTechie commented on Jul 3, 2023

    @JDawgTechie

    Wow, 2 years with no resolution. Good job Powershell team.

  25. Succubyss commented on Jul 7, 2023

    @Succubyss

    I have a suggestion that I believe will alleviate everyone's issues, including those of the PowerShell Imperial High Council.

    Rather than an awkwardly named parameter that only removes the final newline, I instead propose a parameter that would give us what we want while also providing more utility to the function ... the addition of a -Join parameter that could be given the argument of "`n", or whatever else a user might desire.

    Those who want to abolish the final newline from their environment completely would merely need to add $PSDefaultParameterValues['Out-String:Join'] = "`n" (or "`r`n" to their $profile script.

    Obviously, this new parameter would allow a user to join streaming output that needs to be passed through Out-String with something other than newlines, such as a delimiter character that their specific use-case requires.

    It would also be a convenient way to have the output piped directly to Set-Clipboard sans carriage returns without having to encapsulate the entire command in parentheses and using -replace "`r" or .Replace("`r".'') to accomplish the feat.

    Unfortunately, I'm not much of a programmer, so I sincerely hope that someone will eventually poach this idea and submit a push request that implements it – preferably sooner rather than later.

  26. God-damnit-all commented on Aug 8, 2023

    @God-damnit-all
    Contributor

    Slightly off-topic, but I have a question in regards to using a proxy function to solve this problem. Why do proxy functions use $ExecutionContext.InvokeCommand.GetCommand instead of $PSCmdlet.InvokeCommand.GetCommand? My understanding is that $PSCmdlet should always be used instead of $ExecutionContext when using an advanced function, and all the proxy functions are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementResolution-By DesignWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions