在 Windows 批处理文件中访问剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6832203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access clipboard in Windows batch file
提问by random21
Any idea how to access the Windows clipboard using a batch file?
知道如何使用批处理文件访问 Windows 剪贴板吗?
采纳答案by rojo
To set the contents of the clipboard, as Chris Thornton, klaatu, and bunches of othershave said, use %windir%\system32\clip.exe
.
要设置剪贴板的内容,如 Chris Thornton、klaatu 和其他人所说,请使用%windir%\system32\clip.exe
.
Update 2:
更新 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.
for /F
如果需要,使用循环捕获和解析。这不会像下面的 JScript 解决方案那样快速执行,但它确实具有简单的优点。
Updated solution:
更新的解决方案:
Thanks Jonathanfor 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.
感谢 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'));
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)
可以使用 .NET 从 Windows 控制台检索剪贴板文本,而无需任何 3rd 方应用程序。如果您已powershell
安装,您可以通过创建一个虚构的文本框并将其粘贴到其中来检索剪贴板内容。(来源)
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)
如果您没有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());
}
}
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.
这是一个结合了这两种方法的批处理脚本。如果powershell
存在于 中%PATH%
,则使用它。否则,找到 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
回答by Refael Ackermann
Slimming it down (on a new enough version of Windows):
瘦身(在足够新的 Windows 版本上):
set _getclip=powershell "Add-Type -Assembly PresentationCore;[Windows.Clipboard]::GetText()"
for /f "eol=; tokens=*" %I in ('%_getclip%') do set CLIPBOARD_TEXT=%I
- First line declares a
powershell
commandlet. - Second line runs and captures the console output of this commandlet into the
CLIPBOARD_TEXT
enviroment variable (cmd.exe
's closest way to dobash
style backtick`
capture)
- 第一行声明一个
powershell
命令行开关。 - 第二行运行并将此命令行开关的控制台输出捕获到
CLIPBOARD_TEXT
环境变量中(cmd.exe
进行bash
样式反引号`
捕获的最接近方法)
Update 2017-12-04:
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:
感谢@Saintali 指出 PowerShell 5.0 添加Get-Clipboard
为顶级 cmdlet,因此现在可以作为单行代码使用:
for /f "eol=; tokens=*" %I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%I
for /f "eol=; tokens=*" %I in ('powershell Get-Clipboard') do set CLIPBOARD_TEXT=%I
回答by klaatu
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.
clip 命令可以很好地将文本通过管道传输到剪贴板,但它无法从剪贴板读取。在 vbscript/javascript 中有一种方法可以读取/写入剪贴板,但如果 Internet Explorer 这样做,它会使用自动化和不可见的实例,因此它非常胖。
The best tool I've found for working the clipboard from script is Nirsoft's free NirCmd tool.
我发现从脚本处理剪贴板的最佳工具是 Nirsoft 的免费 NirCmd 工具。
http://www.nirsoft.net/utils/nircmd.html
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
它就像一把瑞士军刀,将批处理命令全部放在一个小的 .exe 文件中。对于剪贴板命令,您会说类似
nircmd clipboard [Action] [Parameter]
nircmd 剪贴板 [动作] [参数]
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$ 变量作为参数直接在其任何命令中引用剪贴板内容。Nircmd 中还包含运行其他程序或命令的命令,因此可以使用它以这种方式将剪贴板内容作为参数传递给其他批处理命令。
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.
请注意,即使将特殊的 RTF 或 HTML 副本写入剪贴板,大多数程序也会始终将纯文本副本写入剪贴板,但这些副本是使用不同的剪贴板格式类型作为内容写入的,因此您可能无法访问这些格式除非您的程序从剪贴板明确请求该类型的数据。
回答by Jonathan
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.
如果您想要嵌入 100% 批处理解决方案,则需要从批处理中生成其他语言文件。
回答by emery
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
回答by bbsimonbb
Piping output tothe clipboard is provided by clip, as others have said. To read input fromthe clipboard, use the pclip tool in this bundle. And there's tons of other good stuff in there.
正如其他人所说,将管道输出到剪贴板是由剪辑提供的。读取输入从剪贴板中,使用pclip工具这个包。还有很多其他的好东西。
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
回答by Chris Thornton
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-vistaThe article also contains a link to a free utility (written by Me, I think) called Dos2Clip, which can be used on XP.
对于 Vista 或更高版本,它是内置的。只需将输出通过管道传输到“剪辑”程序即可。这是 一篇文章(由我撰写):http://www.clipboardextender.com/general-clipboard-use/command-window-output-to-clipboard-in-vista 该文章还包含一个免费实用程序的链接(由我,我想)叫做 Dos2Clip,它可以在 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.
更新:与 Dos2Clip 一起的是 Clip2Dos(在同一个 zip 中),它将剪贴板文本发送到标准输出。所以这应该适合你。Pascal 源代码包含在 zip 中。
回答by Srivastav
This might not be the exact answer, but it will be helpful for your Quest.
这可能不是确切的答案,但对您的 Quest 会有所帮助。
Original post: Visit https://groups.google.com/d/msg/alt.msdos.batch/0n8icUar5AM/60uEZFn9IfAJAsked byRoger Hunt Answered byWilliam Allen
原帖:访问https://groups.google.com/d/msg/alt.msdos.batch/0n8icUar5AM/60uEZFn9IfAJRoger Hunt 提问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.
步骤 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=
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.
第 2 步)创建一个空白文本文件(在我的情况下是 H 驱动器中的“CLIP.txt”)或任何地方,确保使用目标文件更新“FN=H:\CLIP.txt”下的 Copy.bat 文件中的路径小路。
That's it.
就是这样。
So, basically when you copy any text from anywhereand run Copy.bat file from desktop, it updates CLIP.txt file with the Clipboard contents in it and saves it.
所以,基本上当你从任何地方复制任何文本并从桌面运行 Copy.bat 文件时,它会用其中的剪贴板内容更新 CLIP.txt 文件并保存它。
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.
我用它从远程连接的机器传输数据,在不同的连接之间复制/粘贴被禁用;其中共享驱动器 (H:) 对所有连接都是通用的。
回答by KorkOoO
Best way I know, is by using a standalone tool called WINCLIP.
我知道的最好方法是使用名为WINCLIP的独立工具。
You can get it from here: Outwit
你可以从这里得到它: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.
- 将剪贴板保存到文件:
winclip -p file.txt
- 将标准输出复制到剪贴板:
winclip -c
例如:Sed 's/find/replace/' file | winclip -c
- 管道剪贴板到 sed:
winclip -p | Sed 's/find/replace/'
使用 winclip 输出(剪贴板)作为另一个命令的参数:
FOR /F "tokens=* usebackq" %%G in ('winclip -p') Do (YOUR_Command %%G )
请注意,如果剪贴板中有多行,此命令将一一解析它们。
You might also want to take a look at getclip& putcliptools: CygUtils for Windowsbut winclip is better in my opinion.
您可能还想查看getclip和putclip工具:CygUtils for Windows,但我认为 winclip 更好。
回答by Garric
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.
Notepad ++,在它应该打开的地方,被注释掉了,因为有时窗口无法访问输入字符,因此您需要确保它处于活动状态。
Of course, it is better to enter characters using the PID of the notebook process, but ...
当然用notebook进程的PID输入字符比较好,但是...
The request from wmic opens for a long time, so do not close the notepad window until the bat file is closed.
来自 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