PoshCode Logo PowerShell Code Repository

Set-Clipboard.ps1 by Lee Holmes 17 months ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2219"></script>download | new post

From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes

  1. #############################################################################
  2. ##
  3. ## Set-Clipboard
  4. ##
  5. ## From Windows PowerShell Cookbook (O'Reilly)
  6. ## by Lee Holmes (http://www.leeholmes.com/guide)
  7. ##
  8. ##############################################################################
  9.  
  10. <#
  11.  
  12. .SYNOPSIS
  13.  
  14. Sends the given input to the Windows clipboard.
  15.  
  16. .EXAMPLE
  17.  
  18. dir | Set-Clipboard
  19. This example sends the view of a directory listing to the clipboard
  20.  
  21. .EXAMPLE
  22.  
  23. Set-Clipboard "Hello World"
  24. This example sets the clipboard to the string, "Hello World".
  25.  
  26. #>
  27.  
  28. param(
  29.     ## The input to send to the clipboard
  30.     [Parameter(ValueFromPipeline = $true)]
  31.     [object[]] $InputObject
  32. )
  33.  
  34. begin
  35. {
  36.     Set-StrictMode -Version Latest
  37.     $objectsToProcess = @()
  38. }
  39.  
  40. process
  41. {
  42.     ## Collect everything sent to the script either through
  43.     ## pipeline input, or direct input.
  44.     $objectsToProcess += $inputObject
  45. }
  46.  
  47. end
  48. {
  49.     ## Launch a new instance of PowerShell in STA mode.
  50.     ## This lets us interact with the Windows clipboard.
  51.     $objectsToProcess | PowerShell -NoProfile -STA -Command {
  52.         Add-Type -Assembly PresentationCore
  53.  
  54.         ## Convert the input objects to a string representation
  55.         $clipText = ($input | Out-String -Stream) -join "`r`n"
  56.  
  57.         ## And finally set the clipboard text
  58.         [Windows.Clipboard]::SetText($clipText)
  59.     }
  60. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me