You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Out-String should not append a trailing newline #14444
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:
(a) Consider a breaking change - assuming it is justified to consider it a Bucket 3: Unlikely Grey Area change - and make Out-Stringnever append a trailing newline.
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.
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.
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.
Reacted by lukeb1961 and Thomas Lee
Reacted by Dan Thompson, Antony Thomas, tt2000, God-damnit-all, Joe Cellucci, Jan Oltmann, Mr Beedell, Roke Julian Lockhart, blaisemGH, Edgar Portales, Wei Shi and 5 more
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 processOut-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.
Reacted by tt2000, Matthew A Cargile, Mr Beedell, Roke Julian Lockhart, Tom Martens, Gus-Esplin and Chris B
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-Contentas-is, without having to resort to the -NoNewlineworkaround.
Reacted by tt2000, God-damnit-all, blaisemGH, Gus-Esplin and Chris B
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
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.
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 '').
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.
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)
Reacted by tt2000, Mr Beedell, Roke Julian Lockhart, Wei Shi and Gus-Esplin
Reacted by Michael Klement, Mathias, tt2000, blaisemGH, Wei Shi and 90jroman
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)
(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.
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:
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:
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".
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).
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>
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
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.
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.
Reacted by Michael Klement, Dan Thompson and 90jroman
The job Out-String was designed to do is to output the formatted text for... which includes.
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
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).
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.
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.
Activity
bpayette commentedon Dec 17, 2020
Out-Stringformats 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.mklement0 commentedon Dec 18, 2020
I don't think it should. Why do you think so?
I would expect:
Get-Dateand
to produce the same output, yet they don't (the latter has an extra newline).
Given that piping to
Out-Stringis 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:
should be equivalent to:
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.
bpayette commentedon Dec 19, 2020
The purpose of
Out-Stringis 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-joinbecause that's it for.mklement0 commentedon Dec 19, 2020
Yes,
-joinis 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-Stringoutput, the trailing newline is an unnecessary nuisance.Each formatted output individually may or may not have trailing newlines (e.g.,
Get-Datevs.'foo').Newlines are only needed as separators between multiple formatted representations, not as a terminators.
Again - there's no justification for
Get-DateandGet-Date | Out-Stringto 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).Countshould report3rather than2, given that there are only two output lines.ExE-Boss commentedon Jan 15, 2021
As I said in #13071 (comment):
mklement0 commentedon Jan 15, 2021
ExE Boss (@ExE-Boss):
Out-Stringis an in-memory operation, whereasSet-Contentis a file operation.When you use
Out-String, you typically want to process the result in memory - otherwise, you'd just use>/Out-Filedirectly.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-Stringbehaved that way, you could later use it withSet-Contentas-is, without having to resort to the-NoNewlineworkaround.kilasuit commentedon Jan 15, 2021
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
mklement0 commentedon Jan 15, 2021
Ryan Yates (@kilasuit), this is primarily about the trailing newline being unhelpful in programmatic processing of
Out-Stringoutput.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-Stringcurrently 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').Countis 3).On printing to the host / saving to a file, you must then suppress the extra trailing newline:
-NoNewLine, if you useOut-File/Set-Content(>is then not an option)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.ExE-Boss commentedon Jan 15, 2021
Out‑Stringalso supports‑NoNewline.mklement0 commentedon Jan 15, 2021
ExE Boss (@ExE-Boss), to quote from the OP:
For instance:
See also: #5108
jazzdelightsme commentedon Jan 16, 2021
I think maybe mklement0 chose
Get-Dateas an example because it produces a simple object that isn't a string (aDateTime), so thatOut-Stringwould be doing "some work" to convert something to a string.But consider even just a plain string!
'asdf'versus
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:
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-Stringcommands, but I think the nerve it hits is quite reasonable: it feels like it ought to be idempotent)17 remaining items
jhoneill commentedon Mar 17, 2023
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)
(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.meproduces 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-stringadding a line break every time looks daft. But it is how$string1 > delete.mefollowed by$string2 >> delete.meavoids 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-stringto be culture aware so I could doget-date | out-string -culture fr-frbecause 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.
mklement0 commentedon Mar 17, 2023
Good point, @ImportTaste. I hope that
(which covers multiple cmdlets, not just
Out-String) will now be considered for implementation.mklement0 commentedon Mar 17, 2023
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:
to just:
That extra newline was never justified - but whether or not it is present doesn't matter if you use
Out-Stringfor actual (complex) object formatting (say,Get-ChildItemoutput), 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-Stringas 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-Stringis 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-Stringoutput - which then amounts to: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-FileorSet-Contentlater, you'll get an extra empty line.CyberBorga commentedon Mar 17, 2023
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:
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".
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:
I hope this helps.
CyberBorga commentedon Mar 17, 2023
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):
Good luck.
jhoneill commentedon Mar 17, 2023
CyberBorga however -stream outputs as many strings as there are objects, so to they may need to be joined together.
mklement0 commentedon Mar 17, 2023
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 … | % ToStringand& $someExternalCli … | Out-String -Stream(note that there's also a built-inossfunction that wrapsOut-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-StringTheOnlyWei commentedon Jun 10, 2023
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
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-Stringgoing forward.jhoneill commentedon Jun 11, 2023
Wei Shi (@TheOnlyWei)
The job
Out-Stringwas designed to do is to output the formatted text for... which includes.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 60format-*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-Stringis emphatically not the same as[string]$xor$x.tostring()for example
None of those is right on all occasions.
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...
'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-hexand
(1234).tostring() | format-hexShow different things.
Yes. As long as people do not understand that
Out-Stringis 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 $xwill do?If $d is a date does that user know when
"The date is " + $dis different from"The date is " + $d.ToString()?(The former does a culture invariant cast, but
ToStringis 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 cmdletout-stringleads 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-NoTrailingNewLineswitch because... " can help us to see things that should be reconsidered (and also applies when if the old decision was perfect).JDawgTechie commentedon Jul 3, 2023
Wow, 2 years with no resolution. Good job Powershell team.
Succubyss commentedon Jul 7, 2023
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
-Joinparameter 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$profilescript.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-Clipboardsans 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.
God-damnit-all commentedon Aug 8, 2023
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.GetCommandinstead 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.