Pipe output to the clipboard using PowerShell
If you have WMF 5.0, PowerShell contains two new cmdlets:
get-clipboard and set-clipboard
EDIT: Please look at question instead for solution.
Here is my solution:
Add-Type -AssemblyName 'System.Windows.Forms'
filter Set-Clipboard {
begin {
$cp = @()
}
process {
$_ | Tee-Object -Variable 'cp0'
$cp = $cp + @($cp0);
}
end {
$str = ($cp | Out-String).ToString();
[Windows.Forms.Clipboard]::Clear();
if ( ($str -ne $null) -and ($str -ne '') ) {
[Windows.Forms.Clipboard]::SetText( $str )
}
$cp = @()
}
}
This collects all the objects in an array, $cp
. We use Tee-Object to redirect the current element, $_
, to both the next process and to store it in the array, $cp
. Lastly, once the process is finished we set the clipboard's text.
I have used it in the following way:
dir -Recurse | Set-Clipboard | Select 'Name'
And it seems to work.
To use a function instead:
function Set-Clipboard-Func {
$str = $input | Out-String
[Windows.Forms.Clipboard]::Clear();
if ( ($str -ne $null) -and ($str -ne '') ) {
[Windows.Forms.Clipboard]::SetText( $str )
}
}
Powershell version 6.1 removed this commandlet, so it is no longer built-in.
Instead, you need to install the ClipboardText package. In Powershell's console type:
Install-Module -Name ClipboardText
Then you can use:
Set-ClipboardText "hello clipboard"
Get-ClipboardText
Here is the github issue with the maintainers of Powershell redirecting you to use the ClipboardText package.