programing

PowerShell을 사용하여 클립보드로 파이프 출력

sourcejob 2023. 10. 31. 21:08
반응형

PowerShell을 사용하여 클립보드로 파이프 출력

편집: 2020년 10월 23일

포스트노트의 답을 보세요.

편집: 2015년 5월 14일

3년 후에, 저의 것을 공유하려고 생각했습니다.ClipboardModule(나는 내가 허락되기를 바랍니다):

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클립보드를 가져오거나 설정할 수 있는 두 가지 방법이 있기 때문입니다.

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이 포함되어 있습니다.

clipboard랑 세트...

편집: 해결책은 질문 대신에 살펴보세요.

해결책은 다음과 같습니다.

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 = @()
    }
}

이렇게 하면 배열된 모든 개체가 수집됩니다.$cp. Tee-Object를 사용하여 현재 요소를 리디렉션합니다.$_, 다음 프로세스와 배열에 저장하기 위해,$cp. 마지막으로 프로세스가 완료되면 클립보드의 텍스트를 설정합니다.

다음과 같은 방법으로 사용했습니다.

dir -Recurse | Set-Clipboard | Select 'Name'

그리고 효과가 있는 것 같습니다.

함수를 대신 사용하려면:

function Set-Clipboard-Func {
    $str = $input | Out-String

    [Windows.Forms.Clipboard]::Clear();

    if ( ($str -ne $null) -and ($str -ne '') ) {
        [Windows.Forms.Clipboard]::SetText( $str )
    }
}

파워셸 버전 6.1에서는 이 명령어가 제거되어 더 이상 내장되어 있지 않습니다.

대신 클립보드를 설치해야 합니다.문자 패키지.파워셸의 콘솔 유형에서:

Install-Module -Name ClipboardText

그러면 다음을 사용할 수 있습니다.

 Set-ClipboardText "hello clipboard"
 Get-ClipboardText

다음은 Powershell의 유지 관리자가 클립보드를 사용하도록 리디렉션하는 github 문제입니다.문자 패키지.

PSv7의 네이티브 클립 cmdlets

$Host
# Results
<#
Name             : ConsoleHost
Version          : 7.0.3
InstanceId       : 54be9bfd-799d-4213-a13a-22403c1d9ed8
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace
#>

Get-Command -Name '*clip*'|Format-Table -a
# Results
<#
CommandType Name                         Version        Source
----------- ----                         -------        ------
Function    Get-Clipboard                1.3.6          PowerShellCookbook
Function    Set-Clipboard                1.3.6          PowerShellCookbook
Function    Start-ClipboardHistoryViewer 0.0            ModuleLibrary
Cmdlet      Get-Clipboard                7.0.0.0        Microsoft.PowerShell.Management
Cmdlet      Set-Clipboard                7.0.0.0        Microsoft.PowerShell.Management
Cmdlet      Set-UDClipboard              2.9.0          UniversalDashboard
Application clip.exe                     10.0.19041.1   C:\WINDOWS\system32\clip.exe
Application ClipRenew.exe                10.0.19041.1   C:\WINDOWS\system32\ClipRenew.exe
Application ClipUp.exe                   10.0.19041.488 C:\WINDOWS\system32\ClipUp.exe
Application rdpclip.exe                  10.0.19041.423 C:\WINDOWS\system32\rdpclip.exe
#>
get-clipboard

텍스트를 순차적으로 입력할 때 줄 바꿈 문자를 생략합니다.사용합니다.

[System.Windows.Forms.Clipboard]::GetText()

종전과 같이

이제 Get-ClipboardSet-Clipboard가 PSv7에 내장되었습니다. 프로필에 다음 기능을 포함할 수 있습니다. "C:\Users<USER_ID>\문서\Windows PowerShell\Microsoft.파워쉘ISE_profile.ps1"

function To-Notepad {
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [object]
        $InputObject
    )
  begin   { $objs = @() }
  process { $objs += $InputObject }
  end {
        $old = Get-clipboard # store current value
        $objs | out-string -width 1000 | Set-Clipboard
        & "notepad2" /c
        sleep -mil 500
        $old | Set-Clipboard # restore the original value
  }
}

그런 다음 다음과 같이 사용합니다.

dir -Path C:\Temp | To-Notepad

언급URL : https://stackoverflow.com/questions/13127578/pipe-output-to-the-clipboard-using-powershell

반응형