使用PowerShell将输出管道传输到剪贴板 [英] Pipe output to the clipboard using PowerShell

查看:74
本文介绍了使用PowerShell将输出管道传输到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PowerShell中,如何将命令的输出通过管道传输到剪贴板,但是

In PowerShell, how do you pipe the output of a command to the clipboard but


  • 仍然能够将数据通过管道传输到更多进程

  • 不依赖于外部应用程序,例如 clip.exe

  • 过滤器,因此我们会立即在命令行上看到输出

三年后,我想我会分享我的 ClipboardModule (希望我可以):

After 3 years, I thought I would share my ClipboardModule (I hope I am allowed to):

Add-Type -AssemblyName System.Windows.Forms

Function Get-Clipboard {
    param([switch]$SplitLines)

    $text = [Windows.Forms.Clipboard]::GetText();

    if ($SplitLines) {
        $xs = $text -split [Environment]::NewLine
        if ($xs.Length -gt 1 -and -not($xs[-1])) {
            $xs[0..($xs.Length - 2)]
        } else {
            $xs
        }
    } else {
        $text
    }
}

function Set-Clipboard {
    $in = @($input)

    $out = 
        if ($in.Length -eq 1 -and $in[0] -is [string]) { $in[0] }
        else { $in | Out-String }

    if ($out) {
        [Windows.Forms.Clipboard]::SetText($out);
    } else {
        # input is nothing, therefore clear the clipboard
        [Windows.Forms.Clipboard]::Clear();
    }
}


function GetSet-Clipboard {
    param([switch]$SplitLines, [Parameter(ValueFromPipeLine=$true)]$ObjectSet)

    if ($input) {
        $ObjectSet = $input;
    }

    if ($ObjectSet) {
        $ObjectSet | Set-Clipboard
    } else {
        Get-Clipboard -SplitLines:$SplitLines
    }
}

Set-Alias cb GetSet-Clipboard

Export-ModuleMember -Function *-* -Alias *

我通常使用 cb 别名(用于 GetSet-Clipboard ),因为这是两种获取或设置剪贴板的方式:

I usually use the cb alias (for GetSet-Clipboard) because it is two way i.e can get or set the clipboard:

cb                # gets the contents of the clipboard
"john" | cb       # sets the clipboard to "john"
cb -s             # gets the clipboard and splits it into lines


推荐答案

如果拥有WMF 5.0,PowerShell将包含两个新的cmdlet:

If you have WMF 5.0, PowerShell contains two new cmdlets:

get-clipboard和set-clipboard

get-clipboard and set-clipboard

这篇关于使用PowerShell将输出管道传输到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆