2

In Powershell, when I run either of the commands below:

echo "abc" | clip
echo "abc" > clip

and paste the output into an editor, then a new line has been appended:

abc
<newline>

How can input be sent to the clip command without having a trailing newline character?

(This happens in Powershell version 5.1 - extracted from $PSversionTable)

bnp887
  • 5,128
  • 2
  • 26
  • 30
  • 2
    Per [this answer](https://stackoverflow.com/a/48388980/4137916), you can't prevent PowerShell from appending a newline if you're using `Write-Output` (which `echo` is an alias for). Fortunately, for this *particular* scenario there's a dedicated `Set-Clipboard` cmdlet which is not so restricted -- `Set-Clipboard "abc"` doesn't append a newline in my tests. – Jeroen Mostert Oct 31 '19 at 10:26
  • 1
    You can always produce a string yourself from output, using various methods (`StringBuilder`, `-join`, `-replace`). This means redirecting or capturing output first. – Jeroen Mostert Oct 31 '19 at 12:08
  • Thanks @JeroenMostert unfortunately, I was just using the `"abc"` as an example. The real problem comes with dynamically generated output; so I'm not able to set a static string with `Set-Clipboard`. However, using `Set-Clipboard` got me thinking about how to do it, and I came up with this: `echo "abc" | ForEach-Object -Process {Set-Clipboard $_.Trim()}` which seems to work ✔ Is there a way to make it less verbose with `StringBuilder`? – bnp887 Oct 31 '19 at 12:09
  • 1
    You can do things like ``[String]::Join("`r`n", (dir |% { $_.Name })) | Set-Clipboard`` -- `String.Join` won't produce a final newline. – Jeroen Mostert Oct 31 '19 at 12:14

2 Answers2

3

This seems to have worked:

echo "abc def" | Set-Clipboard -Value {$_.Trim()}
bnp887
  • 5,128
  • 2
  • 26
  • 30
1

Hmm, if you were using Write-Host you can use the -NoNewline switch

Write-host -NoNewline "Hello World"
Write-host -NoNewline " Continuing on"
  • 1
    Unfortunately useless -- this output is not redirected to another command. If you redirect this to standard output (which is possible from 5.0 onwards, using (`6>&1`) you'll *still* get a newline. – Jeroen Mostert Oct 31 '19 at 11:25