Convert Keith Hill's PowerShell Get-Clipboard and Set-Clipboard to a PSM1 script

Eric Schoonover picture Eric Schoonover · Oct 14, 2009 · Viewed 7.4k times · Source

I'd like to convert Keith Hill's C# implementation of Get-Clipboard and Set-Clipboard into pure PowerShell as a .PSM1 file.

Is there a way to spin up an STA thread in PowerShell as he does in his Cmdlet when working with the clipboard?

The Blog Post
The Code

Answer

hoge picture hoge · Oct 15, 2009

TextBox doesn't require -STA switch.

function Get-ClipBoard {
    Add-Type -AssemblyName System.Windows.Forms
    $tb = New-Object System.Windows.Forms.TextBox
    $tb.Multiline = $true
    $tb.Paste()
    $tb.Text
}


function Set-ClipBoard() {
    Param(
      [Parameter(ValueFromPipeline=$true)]
      [string] $text
    )
    Add-Type -AssemblyName System.Windows.Forms
    $tb = New-Object System.Windows.Forms.TextBox
    $tb.Multiline = $true
    $tb.Text = $text
    $tb.SelectAll()
    $tb.Copy()
}