PowerShell 2.0 – Getting and setting text to and from the clipboard

Updated: now use a temporary file to set text to avoid overflowing command-line buffer

The Windows Clipboard – accessible via System.Windows.Forms.Clipboard – requires an STA thread to read/write to it. By default, the console version of PowerShell 2.0 (i.e. not ISE) starts in MTA mode. This means that read/writing via this class is unreliable. Rather than always starting up console PowerShell in STA mode via the –STA flag, you can use this flag in a sneakier way to get what you want:

function Set-ClipboardText {
        param($text)

        # need to use temp file to avoid exceeding command-line length limit
        $temp = [io.path]::GetTempFileName()

        try {
            set-content -Path $temp -Value $text

            $command = {
                    add-type -an system.windows.forms
                    [System.Windows.Forms.Clipboard]::SetText((get-content $args))
            }
            
            powershell -sta -noprofile -command $command -args $temp

        } finally {
            if ((test-path $temp)) {
                remove-item $temp
            }
        }
}

function Get-ClipboardText {
        $command = {
                add-type -an system.windows.forms
                [System.Windows.Forms.Clipboard]::GetText()
        }
        powershell -sta -noprofile -command $command
}

Essentially we are running PowerShell as a child process temporarily in STA mode, skipping loading the profile and executing a scriptblock.

blog comments powered by Disqus

About the author

Irish, PowerShell MVP, .NET/ASP.NET/SharePoint Developer, Budding Architect. Developer. Montrealer. Opinionated. Montreal, Quebec.

Month List

Page List