Clipboard and PowerShell

If you're reading this, you presumably care very much about getting stuff done quickly.

PowerShell has a couple of commands to access the clipboard, but really, all the fun is in processing content, so you could just as well write your scripts to access files or object streams.

And yet, here you are, trying to access the clipboard directly, typically because you're in the middle of some manual process and you want a bit of automation to help along the way. "Bit of automation" is right up PowerShell's alley.

For the sake of an example, let's say we've copied a tab-delimited table from somewhere, and we want to take all the values in a column, and turn those into a single, semi-colon delimites string. This is what you would do, for example, to take a table of contacts and make them easy to paste into an email To line.

Reading content

Like everything in PowerShell, there is more than one way to go about getting your job done.

The built-in command is Get-Clipboard.

There's just one switch, -raw, which is actually quite important. Without that, PowerShell does its classic sniffing, which means for example that multi-line text is returned as an array of strings, but as a string value if it has no newlines.

Another alternative is to use the WinForms version of the clipboard. The Clipboard type has much finer-grained functionality for dealing with data types, although you can use it to at least make sure you get a plain text representation.

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$t = [System.Windows.Forms.Clipboard]::GetText()

If you perfer loading WPF over WinForms, it also has its own Clipboard class.

Munging content

OK, now you've got a string. Live the dream! Here I'm

$v = get-clipboard -raw
$vals = $v.Split("`r`n")
$mails = [System.Collections.ArrayList]::new()
foreach ($val in $vals) {
  [void] $mails.Add($val.Substring(0, $val.IndexOf("`t")))
}
$together = [String]::Join(";", $mails.ToArray())

Some comments, because we're dealing with a few PowerShell warts here.

Writing content

The last step is easy-peasy: simply use the Set-Clipboard cmdlet to set the value you want, like so.

Set-Clipboard $together

Happy clipboard adventures!

Tags:  codingpowershell

Home