The PowerShell Community Extensions contain a couple handy cmdlets for working with the Windows clipboard: Get-Clipboard
and Out-Clipboard
. One way to use these cmdlets is to copy some text to the clipboard, munge it, and paste it somewhere else. This lets you avoid creating a temporary file just to run a script on it.
Update: Looks like
For example, occasionally I need to copy some C++ source code and paste it into HTML in a <pre>
block. While <pre>
turns off normal HTML formatting, special characters still need to be escaped: <
and >
need to be turned into <
and >
etc. I can copy the code from Visual Studio, run a script html.ps1
from PowerShell, and paste the code into my HTML editor. (I like to use Expression Web.)
The script html.ps1
looks like this.
$a = get-clipboard; $a = $a -replace "&", "&"; $a = $a -replace "<", "<"; $a = $a -replace ">", ">"; $a = $a -replace '"', """ $a = $a -replace "'", "'" out-clipboard $a
So this C++ code
double& x = y; char c = 'k'; string foo = "hello"; if (p < q) ...
turns into this HTML code
double& x = y; char c = 'k'; string foo = "hello"; if (p < q) ...
Of course the PSCX clipboard cmdlets are useful for more than HTML encoding. For example, I wrote a post a few months ago about using them for a similar text manipulation problem.
If you’re going to do much text manipulation, you may want to look at these notes on regular expressions in PowerShell.
The only problem I’ve had with the PSCX clipboard cmdlets is copying formatted text. The cmdlets work as expected when copying plain text. But here’s what I got when I copied the word “snippets” from the CodeProject home page and ran Get-Clipboard
:
Version:0.9 StartHTML:00000136 EndHTML:00000214 StartFragment:00000170 EndFragment:00000178 SourceURL:https://www.codeproject.com/ <html><body> <!--StartFragment-->snippets<!--EndFragment--> </body> </html>
The Get-Clipboard
cmdlet has a -Text
option that you might think would copy content as text, but as far as I can tell the option does nothing. This may be addressed in a future release of PSCX.
You may want to try this Set-Clipboard function and see if it addresses your needs.
http://techibee.com/powershell/powershell-script-to-copy-powershell-command-output-to-clipboard/1316