在 Windows 批处理文件中访问剪贴板

发布于 2024-11-26 10:29:40 字数 34 浏览 2 评论 0原文

知道如何使用批处理文件访问 Windows 剪贴板吗?

Any idea how to access the Windows clipboard using a batch file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

你与清晨阳光 2024-12-03 10:29:41

精简它(在足够新的 Windows 版本上):

set _getclip=powershell "Add-Type -Assembly PresentationCore;[Windows.Clipboard]::GetText()"
for /f "eol=; tokens=*" %I in ('%_getclip%') do set CLIPBOARD_TEXT=%I
  1. 第一行声明一个 powershell commandlet。
  2. 第二行运行并将此命令行开关的控制台输出捕获到 CLIPBOARD_TEXT 环境变量中(cmd.exe 执行 bash 样式反引号的最接近方法` capture)

更新 2017-12-04:

感谢 @Saintali 指出 PowerShell 5.0 添加了 Get-Clipboard 作为顶层cmdlet,因此现在它可以作为单行:

for /f "eol=; tokens=*" %I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%I

Slimming it down (on a new enough version of Windows):

set _getclip=powershell "Add-Type -Assembly PresentationCore;[Windows.Clipboard]::GetText()"
for /f "eol=; tokens=*" %I in ('%_getclip%') do set CLIPBOARD_TEXT=%I
  1. First line declares a powershell commandlet.
  2. Second line runs and captures the console output of this commandlet into the CLIPBOARD_TEXT enviroment variable (cmd.exe's closest way to do bash style backtick ` capture)

Update 2017-12-04:

Thanks to @Saintali for pointing out that PowerShell 5.0 adds Get-Clipboard as a top level cmdlets, so this now works as a one liner:

for /f "eol=; tokens=*" %I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%I

萌面超妹 2024-12-03 10:29:41

Clip 命令可以很好地将文本通过管道传输到剪贴板,但它无法从剪贴板读取。 vbscript / javascript 中有一种方法可以读取/写入剪贴板,但它使用自动化和一个不可见的实例(如果 Internet Explorer 执行此操作),因此它非常丰富。

我发现用于通过脚本操作剪贴板的最佳工具是 Nirsoft 的免费 NirCmd 工具。

http://www.nirsoft.net/utils/nircmd.html

它就像瑞士人批处理命令的军刀全部在一个小 .exe 文件中。对于剪贴板命令,您会说类似

nircmd Clipboard [Action] [Parameter]

另外,您可以使用 ~$clipboard$ 变量作为参数直接引用其任何命令中的剪贴板内容。 Nircmd 中还包含用于运行其他程序或命令的命令,因此可以使用它以这种方式将剪贴板内容作为参数传递给其他批处理命令。

剪贴板操作:

      set - set the specified text into the clipboard. 
 readfile - set the content of the specified text file into the clipboard. 
    clear - clear the clipboard. 
writefile - write the content of the clipboard to a file. (text only) 
  addfile - add the content of the clipboard to a file. (text only) 
saveimage - Save the current image in the clipboard into a file. 
copyimage - Copy the content of the specified image file to the clipboard. 
  saveclp - Save the current clipboard data into Windows .clp file. 
  loadclp - Load Windows .clp file into the clipboard. 

请注意,大多数程序始终会向剪贴板写入纯文本副本,即使它们正在向剪贴板写入特殊的 RTF 或 HTML 副本,但这些程序是使用不同的剪贴板格式类型作为内容写入的,因此您可能无法访问这些格式,除非您的程序明确请求剪贴板中的该类型的数据。

The clip command is good to pipe text to the clipboard, but it can't read from the clipboard. There is a way in vbscript / javascript to read / write the clipboard but it uses automation and an invisible instance if Internet Explorer to do it so its pretty fat.

The best tool I've found for working the clipboard from script is Nirsoft's free NirCmd tool.

http://www.nirsoft.net/utils/nircmd.html

Its like a swiss army knife of batch commands all in one small .exe file. For clipboard commands you would say someting like

nircmd clipboard [Action] [Parameter]

Plus you can directly refer to clipboard contents in any of its commands using its ~$clipboard$ variable as an argument. Nircmd also has commands in it to run other programs or commands from so it is possible to use it to pass the clipboard contents as an argument to other batch commands this way.

Clipboard actions:

      set - set the specified text into the clipboard. 
 readfile - set the content of the specified text file into the clipboard. 
    clear - clear the clipboard. 
writefile - write the content of the clipboard to a file. (text only) 
  addfile - add the content of the clipboard to a file. (text only) 
saveimage - Save the current image in the clipboard into a file. 
copyimage - Copy the content of the specified image file to the clipboard. 
  saveclp - Save the current clipboard data into Windows .clp file. 
  loadclp - Load Windows .clp file into the clipboard. 

Note that most programs will always write a plain text copy to the clipboard even when they are writing a special RTF or HTML copy to the clipboard but those are written as content using a different clipboard format type so you may not be able to access those formats unless your program explicitly requests that type of data from the clipboard.

子栖 2024-12-03 10:29:41

我知道的最好方法是使用名为 WINCLIP 的独立工具。

您可以从这里获取它:Outwit

用法:

  • 将剪贴板保存到文件:winclip -p file.txt

  • 将标准输出复制到剪贴板:winclip -c 例如:Sed 's/find/replace/'文件| winclip -c

  • 通过管道将剪贴板传输到 sed: winclip -p | sed 's/find/replace/'

  • 使用 winclip 输出(剪贴板)作为另一个命令的参数:

    FOR /F "tokens=* usebackq" %%G in ('winclip -p') Do (YOUR_Command %%G ) 请注意,如果剪贴板中有多行,则此命令将一一解析。

您可能还想看看getclip & putclip 工具:CygUtils for Windows 但 winclip 更好我的意见。

Best way I know, is by using a standalone tool called WINCLIP .

You can get it from here: Outwit

Usage:

  • Save clipboard to file: winclip -p file.txt

  • Copy stdout to clipboard: winclip -c Ex: Sed 's/find/replace/' file | winclip -c

  • Pipe clipboard to sed: winclip -p | Sed 's/find/replace/'

  • Use winclip output (clipboard) as an argument of another command:

    FOR /F "tokens=* usebackq" %%G in ('winclip -p') Do (YOUR_Command %%G ) Note that if you have multiple lines in your clipboard, this command will parse them one by one.

You might also want to take a look at getclip & putclip tools: CygUtils for Windows but winclip is better in my opinion.

作妖 2024-12-03 10:29:41

这是使用 mshta 的一种方法:

@echo off
:printClip
for /f "usebackq tokens=* delims=" %%i in (
   `mshta "javascript:Code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(clipboardData.getData('Text'))));"`
) do (
 echo cntent of the clipboard:
 echo %%i
)

直接从控制台访问它的方法相同:

for /f "usebackq tokens=* delims=" %i in (`mshta "javascript:Code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(clipboardData.getData('Text'))));"`) do @echo %i

Here's one way with mshta:

@echo off
:printClip
for /f "usebackq tokens=* delims=" %%i in (
   `mshta "javascript:Code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(clipboardData.getData('Text'))));"`
) do (
 echo cntent of the clipboard:
 echo %%i
)

the same thing for accessing it directly from console:

for /f "usebackq tokens=* delims=" %i in (`mshta "javascript:Code(close(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(clipboardData.getData('Text'))));"`) do @echo %i
葬﹪忆之殇 2024-12-03 10:29:41

在 win 11 中运行的示例批处理文件,我必须阅读本主题中的几个答案才能找到解决方案并获取剪贴板。具体应用是YouTube下载剪贴板中的URL。

@echo off

for /f "eol=; tokens=*" %%I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%%I

youtube-dl -f 18 %CLIPBOARD_TEXT%

pause

An example batch file that is working in win 11, I had to read several answers in this topic to find the solution and get the clipboard. The specific application is YouTube download of the URL in the clipboard.

@echo off

for /f "eol=; tokens=*" %%I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%%I

youtube-dl -f 18 %CLIPBOARD_TEXT%

pause
凉宸 2024-12-03 10:29:41

在 Vista 或更高版本中,它是内置的。只需将输出通过管道传输到“clip”程序即可。
这是我写的一篇文章:
http://www.clipboardextender.com /general-clipboard-use/command-window-output-to-clipboard-in-vista
这篇文章还包含一个名为 Dos2Clip 的免费实用程序(我认为是我编写的)的链接,该实用程序可以在 XP 上使用。

编辑:我发现我已经把问题搞反了,我的解决方案输出到剪贴板,没有读取它。对不起!

更新:与 Dos2Clip 一起的是 Clip2Dos(在同一 zip 中),它将把剪贴板文本发送到标准输出。所以这应该对你有用。 Pascal 源代码包含在 zip 中。

With Vista or higher, it's built in. Just pipe output to the "clip" program.
Here's a writeup (by me):
http://www.clipboardextender.com/general-clipboard-use/command-window-output-to-clipboard-in-vista
The article also contains a link to a free utility (written by Me, I think) called Dos2Clip, which can be used on XP.

EDIT: I see that I've gotten the question backwards, my solution OUTPUTS to the clipboard, doesn't read it. sorry!

Update: Along with Dos2Clip, is Clip2Dos (in the same zip), which will send the clipboard text to stdout. So this should work for you. Pascal source is included in the zip.

錯遇了你 2024-12-03 10:29:41

要从批处理脚本中检索剪贴板内容:不存在“纯粹的”批处理解决方案。

如果您想要嵌入 100% 批处理解决方案,则需要从批处理中生成其他语言文件。

这是一个简短的和批量嵌入解决方案,生成 VB 文件(通常安装在大多数 Windows 上)

To retrive clipboard content from your batch script: there is no "pure" batch solution.

If you want an embed 100% batch solution, you will need to generate the other language file from your batch.

Here is a short and batch embed solution which generate a VB file (Usually installed on most windows)

疯到世界奔溃 2024-12-03 10:29:41

由于所有答案都令人困惑,这里我的代码没有延迟或额外的窗口来打开从剪贴板复制的流链接:

@ECHO OFF
//Name of TEMP TXT Files
SET TXTNAME=CLIP.TXT
//VBA SCRIPT
:: VBS SCRIPT
ECHO.Set Shell = CreateObject("WScript.Shell")>_TEMP.VBS
ECHO.Set HTML = CreateObject("htmlfile")>>_TEMP.VBS
ECHO.TXTPATH = "%TXTNAME%">>_TEMP.VBS
ECHO.Set FileSystem = CreateObject("Scripting.FileSystemObject")>>_TEMP.VBS 
ECHO.Set File = FileSystem.OpenTextFile(TXTPATH, 2, true)>>_TEMP.VBS
ECHO.File.WriteLine HTML.ParentWindow.ClipboardData.GetData("text")>>_TEMP.VBS
ECHO.File.Close>>_TEMP.VBS
cscript//nologo _TEMP.VBS

:: VBS CLEAN UP
DEL _TEMP.VBS

SET /p streamURL=<%TXTNAME%

DEL %TXTNAME%

:: 1) The location of Player
SET mvpEXE="D:\Tools\Programs\MVP\mpv.com"

:: Open stream to video player
%mvpEXE% %streamURL%


@ECHO ON

Since all answers are confusing, here my code without delays or extra windows to open stream link copied from clipboard:

@ECHO OFF
//Name of TEMP TXT Files
SET TXTNAME=CLIP.TXT
//VBA SCRIPT
:: VBS SCRIPT
ECHO.Set Shell = CreateObject("WScript.Shell")>_TEMP.VBS
ECHO.Set HTML = CreateObject("htmlfile")>>_TEMP.VBS
ECHO.TXTPATH = "%TXTNAME%">>_TEMP.VBS
ECHO.Set FileSystem = CreateObject("Scripting.FileSystemObject")>>_TEMP.VBS 
ECHO.Set File = FileSystem.OpenTextFile(TXTPATH, 2, true)>>_TEMP.VBS
ECHO.File.WriteLine HTML.ParentWindow.ClipboardData.GetData("text")>>_TEMP.VBS
ECHO.File.Close>>_TEMP.VBS
cscript//nologo _TEMP.VBS

:: VBS CLEAN UP
DEL _TEMP.VBS

SET /p streamURL=<%TXTNAME%

DEL %TXTNAME%

:: 1) The location of Player
SET mvpEXE="D:\Tools\Programs\MVP\mpv.com"

:: Open stream to video player
%mvpEXE% %streamURL%


@ECHO ON
月光色 2024-12-03 10:29:41

正如其他人所说,将管道输出剪贴板是由clip 提供的。要从剪贴板读取输入,请使用此捆绑包中的 pclip 工具。那里还有很多其他好东西。

例如,您正在学习在线教程,并且想要使用剪贴板的内容创建一个文件...

c:\>pclip > MyNewFile.txt

或者您想要执行复制的命令...

c:\>pclip | cmd

Piping output to the clipboard is provided by clip, as others have said. To read input from the clipboard, use the pclip tool in this bundle. And there's tons of other good stuff in there.

So for example, you're going through an online tutorial and you want to create a file with the contents of the clipboard...

c:\>pclip > MyNewFile.txt

or you want to execute a copied command...

c:\>pclip | cmd
謌踐踏愛綪 2024-12-03 10:29:41

多行

问题已解决,但失望依然存在。

我被迫将一个命令分成两个。

首先,他们很好地理解文本和服务字符,但不理解退格键。

第二个理解退格键,但不理解许多服务字符。

有人能团结他们吗?

Notepad ++ 在应打开的位置被注释掉,因为有时窗口无法输入字符,因此您需要确保它处于活动状态。

当然,最好使用笔记本进程的PID来输入字符,但是......

来自wmic的请求打开了很长一段时间,所以在bat文件关闭之前不要关闭记事本窗口。

    @echo off
    set "like=Microsoft Visual C++"
    set "flag=0"
    start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst
    ( set LF=^
    %= NEWLINE =%
    )
    set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"
    ::------------------
    setlocal enabledelayedexpansion
    for /f "usebackq delims=" %%i in ( `wmic /node:"papa" product where "Name like '%%%like%%%'" get * ^| findstr /r /v "^$"`) do (
        for /f tokens^=1^ delims^=^" %%a in ("%%i") do set str=%%a
        if "!flag!"=="0" ( 
            ::start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst& set "flag=1" 
            for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('{BS}{BS}{BS}{BS}');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set   
            set flag=1
        )
        @set /P "_=%%str%%"<NUL|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
        (echo %%NL%%)|clip  
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set 
    )
    setlocal disabledelayedexpansion

Multiple lines

The problem is resolved, but disappointment remains.

I was forced to split one command into two.

First of them well understands the text and service characters, but does not understand the backspace.

The second understands backspace, but does not understand many service characters.

Can anyone unite them?

Notepad ++, in the place where it should open, is commented out because sometimes the window does not get access to enter characters and therefore you need to make sure that it is active.

Of course, it is better to enter characters using the PID of the notebook process, but ...

The request from wmic opens for a long time, so do not close the notepad window until the bat file is closed.

    @echo off
    set "like=Microsoft Visual C++"
    set "flag=0"
    start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst
    ( set LF=^
    %= NEWLINE =%
    )
    set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"
    ::------------------
    setlocal enabledelayedexpansion
    for /f "usebackq delims=" %%i in ( `wmic /node:"papa" product where "Name like '%%%like%%%'" get * ^| findstr /r /v "^$"`) do (
        for /f tokens^=1^ delims^=^" %%a in ("%%i") do set str=%%a
        if "!flag!"=="0" ( 
            ::start /max C:\"Program Files\Notepad++\notepad++.exe" -nosession -multiInst& set "flag=1" 
            for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('{BS}{BS}{BS}{BS}');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set   
            set flag=1
        )
        @set /P "_=%%str%%"<NUL|clip
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set
        (echo %%NL%%)|clip  
        for /f "delims=" %%i in ('mshta "javascript:new         ActiveXObject('WScript.Shell').SendKeys('^v');close(new         ActiveXObject('Scripting.FileSystemObject'));"') do set 
    )
    setlocal disabledelayedexpansion
空袭的梦i 2024-12-03 10:29:41

还有另一种解决方案,这是一种解决方法,但很简单。您可以从用户获取输入字符串,而不是直接获取剪贴板 - 用户可以从 cmd 窗口粘贴文本(右键单击 cmd 窗口)然后选择粘贴或使用热键:Alt+Space 然后按 E 然后按 P,简而言之,Alt+Space -> E+P)

bat 脚本为:

@ECHO OFF
set /p Input=Enter some text: 
echo %Input%

步骤 0:复制您需要的文本。

步骤1:运行上面的bat脚本。

步骤2:Alt+空格-> E+P,您应该看到剪贴板中的文本已显示,然后按 Enter。完毕!

There is another solution, it's a workaround but simple. Instead of get clipboard directly, you can get input string from user - user can paste the text from cmd window (right click the cmd window then select paste or use hotkey: Alt+Space then press E then press P, in short, Alt+Space -> E+P)

The bat script is:

@ECHO OFF
set /p Input=Enter some text: 
echo %Input%

Step 0: copy the text that you need.

Step 1: run the bat script above.

Step 2: Alt+Space -> E+P, you should see the text from clipboard is shown, press Enter. Done!

智商已欠费 2024-12-03 10:29:41

这可能不是确切的答案,但它会对您的任务有所帮助。

原帖:
访问https://groups.google.com/d/msg/ alt.msdos.batch/0n8icUar5AM/60uEZFn9IfAJ
提问者罗杰·亨特
回答者 William Allen


更简洁的步骤:

步骤 1)使用任何文本编辑器在桌面上创建一个名为 Copy.bat 的“bat”文件,然后复制并粘贴以下代码并保存。

  @ECHO OFF
  SET FN=%1
  IF ()==(%1) SET FN=H:\CLIP.TXT

  :: Open a blank new file
  REM New file>%FN%

  ECHO.set sh=WScript.CreateObject("WScript.Shell")>_TEMP.VBS
  ECHO.sh.Run("Notepad.exe %FN%")>>_TEMP.VBS
  ECHO.WScript.Sleep(200)>>_TEMP.VBS
  ECHO.sh.SendKeys("^+{end}^{v}%%{F4}{enter}{enter}")>>_TEMP.VBS
  cscript//nologo _TEMP.VBS

  ECHO. The clipboard contents are:
  TYPE %FN%

  :: Clean up
  DEL _TEMP.VBS
  SET FN=

步骤 2) 创建一个空白文本文件(在我的例子中为 H 驱动器中的“CLIP.txt”)或任何位置,确保更新“FN=H:\CLIP”下 Copy.bat 文件中的路径.txt' 与您的目标文件路径。

就是这样。

因此,基本上,当您从任何地方复制任何文本并从桌面运行 Copy.bat 文件时,它会使用其中的剪贴板内容更新 CLIP.txt 文件并保存它

用途:

我用它从远程连接的计算机传输数据,其中不同连接之间禁用复制/粘贴;其中共享驱动器 (H:) 对于所有连接都是通用的。

This might not be the exact answer, but it will be helpful for your Quest.

Original post:
Visit https://groups.google.com/d/msg/alt.msdos.batch/0n8icUar5AM/60uEZFn9IfAJ
Asked by Roger Hunt
Answered by William Allen


Much Cleaner Steps:

Step 1) create a 'bat' file named Copy.bat in desktop using any text editors and copy and past below code and save it.

  @ECHO OFF
  SET FN=%1
  IF ()==(%1) SET FN=H:\CLIP.TXT

  :: Open a blank new file
  REM New file>%FN%

  ECHO.set sh=WScript.CreateObject("WScript.Shell")>_TEMP.VBS
  ECHO.sh.Run("Notepad.exe %FN%")>>_TEMP.VBS
  ECHO.WScript.Sleep(200)>>_TEMP.VBS
  ECHO.sh.SendKeys("^+{end}^{v}%%{F4}{enter}{enter}")>>_TEMP.VBS
  cscript//nologo _TEMP.VBS

  ECHO. The clipboard contents are:
  TYPE %FN%

  :: Clean up
  DEL _TEMP.VBS
  SET FN=

Step 2) create a Blank text file (in my case 'CLIP.txt' in H Drive) or anywhere, make sure you update the path in Copy.bat file under 'FN=H:\CLIP.txt' with your destination file path.

That's it.

So, basically when you copy any text from anywhere and run Copy.bat file from desktop, it updates CLIP.txt file with the Clipboard contents in it and saves it.

Uses:

I use it to transfer data from remotely connected machines where copy/paste is disabled between different connections; where shared drive (H:) is common to all Connections.

唠甜嗑 2024-12-03 10:29:40

要设置剪贴板的内容,如 Chris Thornton、klaatu 和一堆其他人说过,使用%windir%\system32\clip.exe


更新 2:

对于快速的单行代码,您可以执行以下操作:

powershell -sta "add-type -as System.Windows.Forms; [windows.forms.clipboard]::GetText()"

如果需要,使用 for /F 循环捕获和解析。这不会像下面的 JScript 解决方案执行得那么快,但它确实具有简单的优点。


更新的解决方案:

感谢 Jonathan 指出神秘的 htmlfile COM 对象用于检索剪贴板。可以调用批处理 + JScript 混合来检索剪贴板的内容。事实上,它只需要一行 JScript 和一行 cscript 即可触发它,并且比之前提供的 PowerShell / .NET 解决方案要快得多。

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "getclip=cscript /nologo /e:JScript "%~f0""

rem // If you want to process the contents of the clipboard line-by-line, use
rem // something like this to preserve blank lines:
for /f "delims=" %%I in ('%getclip% ^| findstr /n "^"') do (
    setlocal enabledelayedexpansion
    set "line=%%I" & set "line=!line:*:=!"
    echo(!line!
    endlocal
)

rem // If all you need is to output the clipboard text to the console without
rem // any processing, then remove the "for /f" loop above and uncomment the
rem // following line:
:: %getclip%

goto :EOF

@end // begin JScript hybrid chimera
WSH.Echo(WSH.CreateObject('htmlfile').parentWindow.clipboardData.getData('text'));

旧的解决方案:

可以使用 .NET 从 Windows 控制台检索剪贴板文本,而无需任何第三方应用程序。如果您安装了 powershell,您可以通过创建一个虚构的文本框并将其粘贴到其中来检索剪贴板内容。 (来源

Add-Type -AssemblyName System.Windows.Forms
$tb = New-Object System.Windows.Forms.TextBox
$tb.Multiline = $true
$tb.Paste()
$tb.Text

如果您不这样做如果没有 powershell,您仍然可以编译一个简单的 .NET 应用程序以将剪贴板文本转储到控制台。这是一个 C# 示例。 (灵感

using System;
using System.Threading;
using System.Windows.Forms;
class dummy {
    [STAThread]
    public static void Main() {
        if (Clipboard.ContainsText()) Console.Write(Clipboard.GetText());
    }
}

这是一个结合了这两种方法的批处理脚本。如果 %PATH% 中存在 powershell,请使用它。否则,找到 C# 编译器/链接器并构建临时 .NET 应用程序。正如您在批处理脚本注释中看到的,您可以使用 for /f 循环捕获剪贴板内容,或者简单地将它们转储到控制台。

:: clipboard.bat
:: retrieves contents of clipboard

@echo off
setlocal enabledelayedexpansion

:: Does powershell.exe exist within %PATH%?
for %%I in (powershell.exe) do if "%%~$PATH:I" neq "" (
    set getclip=powershell "Add-Type -AssemblyName System.Windows.Forms;$tb=New-Object System.Windows.Forms.TextBox;$tb.Multiline=$true;$tb.Paste();$tb.Text"
) else (
rem :: If not, compose and link C# application to retrieve clipboard text
    set getclip=%temp%\getclip.exe
    >"%temp%\c.cs" echo using System;using System.Threading;using System.Windows.Forms;class dummy{[STAThread]
    >>"%temp%\c.cs" echo public static void Main^(^){if^(Clipboard.ContainsText^(^)^) Console.Write^(Clipboard.GetText^(^)^);}}
    for /f "delims=" %%I in ('dir /b /s "%windir%\microsoft.net\*csc.exe"') do (
        if not exist "!getclip!" "%%I" /nologo /out:"!getclip!" "%temp%\c.cs" 2>NUL
    )
    del "%temp%\c.cs"
    if not exist "!getclip!" (
        echo Error: Please install .NET 2.0 or newer, or install PowerShell.
        goto :EOF
    )
)

:: If you want to process the contents of the clipboard line-by-line, use
:: something like this to preserve blank lines:
for /f "delims=" %%I in ('%getclip% ^| findstr /n "^"') do (
    set "line=%%I" & set "line=!line:*:=!"
    echo(!line!
)

:: If all you need is to output the clipboard text to the console without
:: any processing, then remove the above "for /f" loop and uncomment the
:: following line:

:: %getclip%

:: Clean up the mess
del "%temp%\getclip.exe" 2>NUL
goto :EOF

To set the contents of the clipboard, as Chris Thornton, klaatu, and bunches of others have said, use %windir%\system32\clip.exe.


Update 2:

For a quick one-liner, you could do something like this:

powershell -sta "add-type -as System.Windows.Forms; [windows.forms.clipboard]::GetText()"

Capture and parse with a for /F loop if needed. This will not execute as quickly as the JScript solution below, but it does have the advantage of simplicity.


Updated solution:

Thanks Jonathan for pointing to the capabilities of the mysterious htmlfile COM object for retrieving the clipboard. It is possible to invoke a batch + JScript hybrid to retrieve the contents of the clipboard. In fact, it only takes one line of JScript, and a cscript line to trigger it, and is much faster than the PowerShell / .NET solution offered earlier.

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "getclip=cscript /nologo /e:JScript "%~f0""

rem // If you want to process the contents of the clipboard line-by-line, use
rem // something like this to preserve blank lines:
for /f "delims=" %%I in ('%getclip% ^| findstr /n "^"') do (
    setlocal enabledelayedexpansion
    set "line=%%I" & set "line=!line:*:=!"
    echo(!line!
    endlocal
)

rem // If all you need is to output the clipboard text to the console without
rem // any processing, then remove the "for /f" loop above and uncomment the
rem // following line:
:: %getclip%

goto :EOF

@end // begin JScript hybrid chimera
WSH.Echo(WSH.CreateObject('htmlfile').parentWindow.clipboardData.getData('text'));

Old solution:

It is possible to retrieve clipboard text from the Windows console without any 3rd-party applications by using .NET. If you have powershell installed, you can retrieve the clipboard contents by creating an imaginary textbox and pasting into it. (Source)

Add-Type -AssemblyName System.Windows.Forms
$tb = New-Object System.Windows.Forms.TextBox
$tb.Multiline = $true
$tb.Paste()
$tb.Text

If you don't have powershell, you can still compile a simple .NET application to dump the clipboard text to the console. Here's a C# example. (Inspiration)

using System;
using System.Threading;
using System.Windows.Forms;
class dummy {
    [STAThread]
    public static void Main() {
        if (Clipboard.ContainsText()) Console.Write(Clipboard.GetText());
    }
}

Here's a batch script that combines both methods. If powershell exists within %PATH%, use it. Otherwise, find the C# compiler / linker and build a temporary .NET application. As you can see in the batch script comments, you can capture the clipboard contents using a for /f loop or simply dump them to the console.

:: clipboard.bat
:: retrieves contents of clipboard

@echo off
setlocal enabledelayedexpansion

:: Does powershell.exe exist within %PATH%?
for %%I in (powershell.exe) do if "%%~$PATH:I" neq "" (
    set getclip=powershell "Add-Type -AssemblyName System.Windows.Forms;$tb=New-Object System.Windows.Forms.TextBox;$tb.Multiline=$true;$tb.Paste();$tb.Text"
) else (
rem :: If not, compose and link C# application to retrieve clipboard text
    set getclip=%temp%\getclip.exe
    >"%temp%\c.cs" echo using System;using System.Threading;using System.Windows.Forms;class dummy{[STAThread]
    >>"%temp%\c.cs" echo public static void Main^(^){if^(Clipboard.ContainsText^(^)^) Console.Write^(Clipboard.GetText^(^)^);}}
    for /f "delims=" %%I in ('dir /b /s "%windir%\microsoft.net\*csc.exe"') do (
        if not exist "!getclip!" "%%I" /nologo /out:"!getclip!" "%temp%\c.cs" 2>NUL
    )
    del "%temp%\c.cs"
    if not exist "!getclip!" (
        echo Error: Please install .NET 2.0 or newer, or install PowerShell.
        goto :EOF
    )
)

:: If you want to process the contents of the clipboard line-by-line, use
:: something like this to preserve blank lines:
for /f "delims=" %%I in ('%getclip% ^| findstr /n "^"') do (
    set "line=%%I" & set "line=!line:*:=!"
    echo(!line!
)

:: If all you need is to output the clipboard text to the console without
:: any processing, then remove the above "for /f" loop and uncomment the
:: following line:

:: %getclip%

:: Clean up the mess
del "%temp%\getclip.exe" 2>NUL
goto :EOF
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文