powershellclipboard

Set-Clipboard only remembering the last value when called in rapid succession


I am trying to create a powershell snippet that will copy the first column of a multi-line piped input to clipboard.

The intended usage is: kubectl get pods | copyfirst.
This should allow me to have all pod names in the clipboard, and use Win+V to select the individual pod name that I need.

What I have so far is:

function copyfirst {
    [CmdletBinding()]Param([Parameter(ValueFromPipeline)]$Param)
    process {
        $Param.Split(" ")[0] | Set-Clipboard
    }
}

The problem is - this only copies the last entry to clipboard, while all the others are ignored.

If I change Set-Clipboard to some other command - it works as intended. For example echo outputs all pod names, not just the last one.


Solution

  • I think mklement0's answer was the right one to begin with and I personally was not aware of this Win + V clipboard functionality. So, you were right, as it seems it can't capture the history when done in rapid succession.

    By adding Start-Sleep it works fine:

    function copyfirst {
        [CmdletBinding()]
        param(
            [Parameter(ValueFromPipeline)]
            [object[]] $Param
        )
    
        process {
            $Param.Split(' ')[0] | Set-Clipboard
            Start-Sleep -Milliseconds 250
        }
    }
    
    @'
    string1 string4
    string2 string5
    string3 string6
    '@ -split '\r?\n' | copyfirst
    

    It should capture string1, string2 and string3.

    Tweak the sleep timer until it's not too slow and it can capture everything.


    After some testing, seems like Start-Sleep can be reduced to -Milliseconds 250, lower than that would produce inconsistent results.