Giter VIP home page Giter VIP logo

clipboardtext's Introduction

PowerShell Gallery license

Clipboard text support for PowerShell Core (cross-platform) and Windows PowerShell v2-v4

ClipboardText is a cross-edition, cross-platform PowerShell module that provides support for copying text to and retrieving text from the system clipboard, via the Set-ClipboardText and Get-ClipboardText cmdlets.

It is useful in the following scenarios:

  • Use with PowerShell Core on (hopefully) all supported platforms.

    • As of v6.1, PowerShell Core doesn't ship with clipboard cmdlets.
    • This module fills this gap, albeit only with respect to text.
    • The implementation relies on external utilities (command-line programs) on all supported platforms:
      • Windows: clip.exe (built in)
      • macOS: pbcopy and pbpaste (built in)
      • Linux: xclip (requires installation via the system's package manager; e.g. sudo apt-get install xclip; available on X11-based freedesktop.org-compliant desktops, such as on Ubuntu)
  • Use with older versions of Windows PowerShell.

    • Only since v5.0 does Windows PowerShell ship with Set-Clipboard and Get-Clipboard cmdlets.
    • This module fills the gap for v2-v4, albeit only with respect to text.
    • For implementing backward-compatible functionality, you may also use this module in v5+, in which case this module's cmdlets call the built-in ones behind the scenes.
    • On older versions, the implementation uses Windows Forms .NET types behind the scenes (namespace System.Windows.Forms)
  • Use in universal scripts.

    • Universal scripts are scripts that run on both Windows PowerShell and Powershell Core, on all supported platforms, including older versions of Windows PowerShell; in this case, down to version 2.

Installation

Installation from the PowerShell Gallery

Prerequisite: The PowerShellGet module must be installed (verify with Get-Command Install-Module).
PowerShellGet comes with PowerShell version 5 or higher; it is possible to manually install it on versions 3 and 4 - see the docs.

  • Current-user-only installation:
# Installation for the current user only.
PS> Install-Module ClipboardText -Scope CurrentUser
  • All-users installation (requires elevation / sudo):
# Installation for ALL users.
# IMPORTANT: Requires an ELEVATED session:
#   On Windows: 
#     Right-click on the Windows PowerShell icon and select "Run as Administrator".
#   On Linux and macOS:
#     Run `sudo pwsh` from an existing terminal.
ELEV-PS> Install-Module ClipboardText -Scope AllUsers

See also: this repo's page in the PowerShell Gallery.

Manual Installation

If you're still using PowerShell v2, manual installation is your only option.

Clone this repository (as a subfolder) into one of the directories listed in the $env:PSModulePath variable; e.g., to install the module in the context of the current user, choose the following parent folders:

  • Windows:
    • Windows PowerShell: $HOME\Documents\WindowsPowerShell\Modules
    • PowerShell Core: $HOME\Documents\PowerShell\Modules
  • macOs, Linux (PowerShell Core):
    • $HOME/.local/share/powershell/Modules

As long as you've cloned into one of the directories listed in the $env:PSModulePath variable - copying to some of which requires elevation / sudo - and as long your $PSModuleAutoLoadingPreference is not set (the default) or set to All, calling Set-ClipboardText or Get-ClipboardText should import the module on demand - except in PowerShell v2.

To explicitly import the module, run Import-Module <path/to/module-folder>.

Example: Install as a current-user-only module:

Note: Assumes that git is installed.

# Switch to the parent directory of the current user's modules.
Set-Location $(if ($env:OS -eq 'Windows_NT') { "$HOME\Documents\{0}\Modules" -f ('WindowsPowerShell', 'PowerShell')[[bool]$IsCoreClr] } else { "$HOME/.local/share/powershell/Modules" })
# Clone this repo into subdir. 'ClipboardText'; --depth 1 gets only the latest revision.
git clone --depth 1 --quiet https://github.com/mklement0/ClipboardText

On Windows PowerShell v2, you must now explicitly load the module:

Import-Module -Verbose .\ClipboardText

Run Set-ClipboardText -? to verify that installation succeeded and that the module is loaded on demand (PSv3+): you should see brief CLI help text.

Usage

In short:

  • Set-ClipboardText copies strings as-is; output from commands is copied using the same representation you see in the console, essentially obtained via Out-String; e.g.:
# Copy the full path of the current filesystem location to the clipbard:
$PWD.Path | Set-ClipboardText

# Copy the names of all files in the current directory to the clipboard:
Get-ChildItem -File -Name | Set-ClipboardText
  • Get-ClipboardText retrieves text from the clipboard as an array of lines by default; use -Raw to request the text as-is, as a potentially multi-line string.
# Retrieve text from the clipboard as a single string and save it to a file:
Get-ClipboardText -Raw > out.txt

# Retrieve text from the clipboard as an array of lines and prefix each with
# a line number:
Get-ClipboardText | ForEach-Object { $i=0 } { '#{0}: {1}' -f (++$i), $_ }

For more, consult the built-in help after installation:

# Concise command-line help with terse description and syntax diagram.
Get-ClipboardText -?
Set-ClipboardText -?

# Full help, including parameter descriptions and details and examples.
Get-Help -Full Get-ClipboardText
Get-Help -Full Set-ClipboardText

# Examples only
Get-Help -Examples Get-ClipboardText
Get-Help -Examples Set-ClipboardText

License

See LICENSE.md.

Changelog

See CHANGELOG.md.

clipboardtext's People

Contributors

mklement0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

clipboardtext's Issues

With Windows PowerShell, complains about missing xclip the first it's used if StrictMode is in effect

My PowerShell profile invokes

Set-StrictMode -Version Latest

As a side effect, the first time I use the module in a PS session (i.e. when the module gets auto-loaded), I get a message telling me that "xclip" is not installed... whereas I'm running Windows PowerShell 5.1 on Windows 10 ;-)

Here's the culprit: CheckPrereqs.ps1 tests the value of $IsLinux, which doesn't exist in Windows PowerShell. If StrictMode is not in effect, the test works, because $IsLinux silently evaluates to $null.

But if StrictMode is in effect, the test fails...

CMD message if working directory is a UNC path

Thanks for this awesome module! Removes one more reason for not switching to PowerShell Core 6.x ;-)

I'd like to report a relatively minor issue.

If the current working directory is a UNC path, invoking Set-ClipboardText results in a message from CMD:

PS //pnjnas/public/olddiscs> (pwd).ProviderPath
\\pnjnas\public\olddiscs
PS //pnjnas/public/olddiscs> "foo" | Set-ClipboardText
'\\pnjnas\public\olddiscs'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.

The solution is quite simple: wrap the invocation of CMD in a piece of code that preserves the current working directory, switches to some location on a non-network drive, and last restores the initial working directory, something like:

$oldpwd = (pwd).path
cd c:/ # ideal is to find a local drive instead of hardcoding c:
cmd.exe /c clip.exe '<' $tmpFile
cd $oldpwd

make it clear in readme that this runs on ALL PowerShell versions

Initially, I was not sure if this module runs on Windows PowerShell v.5. I tested it and it works fine.

This should be clear from readme.md, because that means module can be used in universal PowerShell scripts. Universal PowerShell scripts are the ones which run on both Windows PowerShell and PowerShell Core.

version 5.1 fails in MTA mode

If PowerShell v.5.1 is running in MTA mode, code will fail on

Set-Clipboard -Value ($allText, $null)[$allText.Length -eq 0]

Error is:

Set-Clipboard : Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

Steps to reproduce

Start PowerShell in MTA mode

powershell.exe -MTA

Start tests

Invoke-Pester

Expected results: Tests are successful

Actual results: Tests fail with error specified above.

Possible resolution

Check for STA/MTA before checking the version. Then execute 5.1 code only if running in STA mode.

Something like:

if (test-WindowsPowerShell) { # *Windows PowerShell*
    Add-Type -AssemblyName System.Windows.Forms
    $STAMode = [threading.thread]::CurrentThread.ApartmentState.ToString() -eq 'STA'
    if (($PSVersionTable.PSVersion -ge [version] '5.1.0') -and $STAMode) { # Ps*Win* v5.1+ now has Get-Clipboard / Set-Clipboard cmdlets.
...

The same should be done in both Get and Set commandlet. Still tests with the empty string will fail. But that is another issue.

Remove dependency on Windows Script Host

I tried using this on windows and I get an error because the script host has been disabled through a domain policy by our IT department. Would it not be possible to P/Invoke relevant APIs on windows instead?

Can clipboard usage in a spawned shell be supported as well?

$ Get-ClipboardText
https://github.com/mklement0/ClipboardText/issues/new
$ ([string] (Get-ClipboardText))
https://github.com/mklement0/ClipboardText/issues/new
$ .\pwsh.exe -Command Get-ClipboardText
https://github.com/mklement0/ClipboardText/issues/new
$ .\pwsh.exe -Command Start-Process -Wait -NoNewWindow pwsh.exe -ArgumentList Get-ClipboardText
The argument 'Get-ClipboardText' is not recognized as the name of a script file. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

The error message is the same as when the clipboard contains no item.

EDIT:
To be more clear, is it possible to retain PS5 Get-Clipboard behavior?

$ .\pwsh.exe -Command Start-Process -Wait -NoNewWindow powershell.exe -ArgumentList Get-Clipboard
https://github.com/mklement0/ClipboardText/issues/new

'clip.exe' is not recognized as an internal or external command

Problem
For whatever reason I nowadays get below error message when running Set-ClipboardText from Powershell Core:

VERBOSE: Windows: using clip.exe
'clip.exe' is not recognized as an internal or external command,
operable program or batch file.
Set-ClipboardText : Invoking the platform-specific clipboard utility failed unexpectedly.

Running clip.exe works fine but not when called via cmd.exe:

C:\>clip.exe /?

CLIP

Description:
    Redirects output of command line tools to the Windows clipboard.
    This text output can then be pasted into other programs.

Parameter List:
    /?                  Displays this help message.

Examples:
    DIR | CLIP          Places a copy of the current directory
                        listing into the Windows clipboard.

    CLIP < README.TXT   Places a copy of the text from readme.txt
                        on to the Windows clipboard.
C:\>cmd.exe /c clip.exe /?
'clip.exe' is not recognized as an internal or external command,
operable program or batch file.

Solution
Works fine when using Get-Command to resolve full path

[string]$clipExePath = (Get-Command clip.exe).Path;
cmd.exe /c $clipExePath '<' $tmpFile

Enable Set-Clipboard and Get-Clipboard aliases

In PS, the commands included out of the box are Set-Clipboard and Get-Clipboard. PS Core doesn't have such commands out of the box but this awesome module makes that possible, however it does so with slightly different names.

In order to ensure I can run the same scripts in PS and PS Core without modifications and without extra branching logic, the clipboard commands should have the same name.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.