when I use this command pwsh -c echo hello
in cmd I get the following output:
C:\>pwsh -c echo hello
hello
C:\>
I do not get that line break at the end when I run it on powershell:
PS C:\> pwsh -c echo hello
hello
PS C:\>
So I think the problem is in cmd. I know this is not such a problem and have an easy fix but I have some programs that uses cmd to access powershell and removing that line break is not that fun. So is there any fix to prevent cmd to add that line ?
CodePudding user response:
Mofi has provided the crucial pointers in comments:
When executing a command interactively,
cmd.exe
unconditionally appends a a newline (line break) to the command's output, presumably for readability and perhaps also to ensure that the next prompt always starts on a new line.- This applies irrespective of what that command is. In other words: It doesn't matter that your command happens to be a PowerShell command.
However, that trailing newline does not become part of the command's output, therefore programmatic processing of a command's output is not affected, such as when you redirect
>
to a file or process the output lines one by one withfor /f
.In other words: for programmatic processing you need not remove the trailing newline, because it isn't part of the actual command output.
Conversely, if you really need to in effect suppress the trailing newline for display, you'll have to modify the command's output - if that is even an option - so that the output itself doesn't end in a newline, as shown in this SuperUser answer for
cmd.exe
's ownecho
command; for PowerShell, you could dopwsh -c Write-Host -NoNewLine hello
.
Edge case:
When capturing output from a batch file that is running without @echo off
(or with echo on
) - in which case the trailing newlines do become part of the output - you can filter out empty lines by piping to findstr /r /v /c:"^$"
(as also shown in the linked answer); e.g.
foo.cmd | findstr /r /v /c:"^$"
However, note that all empty lines are filtered out this way - potentially including actual empty lines in the output from commands executed by the batch file.
If preventing that is required, a more sophisticated approach is required, which, however (a) relies on the standard prompt string (e.g., C:\>
) being used and (b) can still yield false positives:
foo.cmd | powershell -nop -c "@($Input) -join \"`n\" -replace '\n(?=[a-z]:\\.*?>)'"
Finally note that if you execute the above commands without capturing or redirecting their output, their overall output in the cmd.exe
console will again have a trailing newline.