wolfgang ziegler


„make stuff and blog about it“

Redirect Command Line Output to the Clipboard

July 26, 2013

Today I stumbled over an awesome Windows Tool. It’s called clip.exe and apparently it has been around since Windows Vista. I just did not happen to realize until now.

What it does, is actually quite simple: It accepts textual input of any kind and puts it into the Windows clipboard. This in turn means, that we can pipe arbitrary command line output to clip.exe and have it in the clipboard then.

Let’s fire up cmd.exe and try it out.

> echo “Hello Clipboard” | clip

image

This call actually puts the text “Hello Clipboard” into the Windows clipboard.

This is really useful in certain situations. Let’s say you quickly need to put a list of all .png files in a folder into some document. This command line does the trick:

> dir *.png /B | clip

image

With clip.exe, it’s also possible to read the content of an entire file (e.g bla.txt) into the clipboard.

> clip < bla.txt

image


What about PowerShell?

Of course, clip.exe can be also used with PowerShell. But PowerShell, being PowerShell, also allows us reading the content of the clipboard back in again.

PS C:\> echo "Hello Clipboard from PS!" | clip.exe
PS C:\> Add-Type -AssemblyName System.Windows.Forms
PS C:\> [System.Windows.Forms.Clipboard]::GetText()

image

This is a bit verbose though and can easily be turned into a PowerShell function, which we call Get-ClipboardText.

PS C:\> echo "Hello Clipboard from PS!" | clip.exe
PS C:\> function Get-ClipboardText {
>> Add-Type -AssemblyName System.Windows.Forms
>> [System.Windows.Forms.Clipboard]::GetText()
>> }
>>
PS C:\> Get-ClipboardText
Hello Clipboard from PS!

We could now also implement a Set-ClipboardText function quite easily, but there’s no point in doing that since that’s what clip.exe is for, right?

So, that’s it. Have fun with clip.exe!