3

In a batch script, I wish to save the clipboard text into a variable. Having searched it seems that this is not possible without 3rd-party tools. Well I have nircmd, and one of its commands is:

"consolewrite [text] Sends the specified text to the standard output (stdout)."

I was hoping I could achieve my goal with the following straightforward line:

    FOR /F "tokens=* USEBACKQ" %%F IN (`nircmd.exe consolewrite ~$clipboard$`) DO (SET varCB=%%F)

which in theory would see nircmd write the clipboard contents to STDOUT, and then the for command would save this output into varCB. But it doesn't work.

UPDATE: Actually that line now works. It will place the text in the clipboard into varCB. Must have made some error in my initial testing.

UPDATE 2: It has been pointed out that if there are multiple lines of text on the clipboard, the above code will only store the last line in the variable varCB. If your clipboard text has multiple lines you can store each line in its own variable with the following code:

    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET count=1
    FOR /F "tokens=* USEBACKQ" %%F IN (`nircmd.exe consolewrite ~$clipboard$`) DO (
      SET varCB!count!=%%F
      SET /a count=!count!+1
    )
    ECHO %varCB1%
    ECHO %varCB2%
    ECHO %varCB3%
    [...]
    ENDLOCAL

(adapted from a code I copied long ago, I forget from where unfortunately.)

UPDATE 3: It has also been pointed out that my use of the term "3rd-party tools" above is inaccurate. I simply meant that other applications or scripting languages would be needed to achieve the goal (such as PowerShell or NirCMD). Of course Some of these tools might already be included with Win10 and so are not technically "3rd-party". Sorry about that!

TechHorse
  • 269
  • 2
  • 13
  • When you downloaded Nircmd, did you run nircmd.exe as Administrator, and agree to copy Nircmd.exe to the C:\Windows directory? That is needed so that Nircmd.exe is on your PATH. – Michael Harvey Jan 01 '22 at 15:44
  • @Michael Harvey It's path is "C:\Windows\nircmd.exe". However see the update. For some reason the for command I referred to above now works. Must have been an error in how I was testing it. Will answer my own question shortly. – TechHorse Jan 01 '22 at 16:10
  • The command you showed prints the clipboard text to the console on my system. See answer below. – Michael Harvey Jan 01 '22 at 16:12
  • This is odd because FOR /F swallows the stdout (console) output of a command, which ought also to show in the console. A thought - just guessing - are you using one of those weird 3rd party cmd window replacements, like Cmder, ConEmu, ConsoleZ, etc, or have some console enhancer running? Also - another guess - if using standard Windows console. do your console and Nircmd match for bitness (i.e. both 32 or 64 bit)? In a 64 bit Windows system, you have a 32 bit console `C:\Windows\SysWOW64\cmd.exe` and a 64 bit one `C:\Windows\System32\cmd.exe`, and Nircmd comes in 32 and 64 bit versions. – Michael Harvey Jan 01 '22 at 21:48
  • I am not sure about the CMD bits as I just create bat files and run them. You'd have to ask Win10 what it is running them with. Nircmd would be the 64-bit version, and I have not changed anything else from what shipped with my PC. – TechHorse Jan 01 '22 at 21:58

4 Answers4

2

In a batch script, I wish to save the clipboard text into a variable. Having searched it seems that this is not possible without 3rd-party tools.

So sorry to say, but this is not true:


  • PowerShell paste clipboard:
Get-Clipboard|Foreach{$_} 

// or using aliases, shorter: gcb|?{$_}
  • VBScript paste clipboard:
WScript.Echo CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")
  • Bat + Powershell
powershell -nOp -c  "Get-Clipboard|Foreach{$_}"

  • You don't need third-party tools to get the however of your clipboard, which is one or more lines:
@echo off 

for /f usebackq^tokens^=1*delims^=: %%i in (`(
powershell -nOp -c "gcb|%%{$_}"^)^|findstr /nr .
   `)do set "_vbCB_%%~i=%%~j" && set "_upto=%%~i"
    
for /l %%L in (1 1 %_upto%)do call echo\_vbCB_%%L: %%_vbCB_%%~L%%

  • Content on my ClipBoard:


Lorem ipsum dolor sit amet. Sed iure harum et esse error et velit earum. 
Et dolor perspiciatis id veniam dolor cum galisum asperiores. 
Ab doloremque omnis sed harum explicabo ut galisum 
veniam ut voluptas facere.

Sed amet corporis eos magnam voluptatem sed dolor alias. Et facere esse 
ea voluptates odit aut alias pariatur. Aut molestiae quam et saepe 
corrupti id quia facilis. Est labore temporibus qui eaque labore ab 
ipsa voluptatibus vel dolores galisum non aliquid earum id beatae 
rerum.

Eos nobis consequatur est accusantium sapiente et illum velit et 
libero quasi est consequatur fuga ea sunt molestias. Id enim vitae 
sed dolor similique qui voluptatem autem. Aut sunt perferendis in 
aperiam aspernatur nam assumenda aliquam hic laboriosam galisum.

  • Outputs:
_vbCB_1:
_vbCB_2:
_vbCB_3: Lorem ipsum dolor sit amet. Sed iure harum et esse error et velit earum.
_vbCB_4: Et dolor perspiciatis id veniam dolor cum galisum asperiores.
_vbCB_5: Ab doloremque omnis sed harum explicabo ut galisum
_vbCB_6: veniam ut voluptas facere.
_vbCB_7:
_vbCB_8: Sed amet corporis eos magnam voluptatem sed dolor alias. Et facere esse
_vbCB_9: ea voluptates odit aut alias pariatur. Aut molestiae quam et saepe
_vbCB_10: corrupti id quia facilis. Est labore temporibus qui eaque labore ab
_vbCB_11: ipsa voluptatibus vel dolores galisum non aliquid earum id beatae
_vbCB_12: rerum.
_vbCB_13:
_vbCB_14: Eos nobis consequatur est accusantium sapiente et illum velit et
_vbCB_15: libero quasi est consequatur fuga ea sunt molestias. Id enim vitae
_vbCB_16: sed dolor similique qui voluptatem autem. Aut sunt perferendis in
_vbCB_17: aperiam aspernatur nam assumenda aliquam hic laboriosam galisum.

Obs.: The first 2 lines are purposely blank to show that you get the entire contents of the ClipBoard, including blank lines, no matter where they are.

Io-oI
  • 7,588
  • 3
  • 12
  • 41
  • 2
    He *should have* said.. "this is not possible within batch itself". ;) Nice answer. +1 for the ipsum. I myself would do this in a `call : – Señor CMasMas Jan 01 '22 at 22:37
  • @SeñorCMasMas Thanks for the comment, I'll see this option, and Happy New Year Code New mi señor! – Io-oI Jan 01 '22 at 22:40
  • Yes I meant simply that the use of other tools would be needed. Some of these tools may very well come packaged with Win10, as is the case with PowerShell. Still, if you know that your expected clipboard text is only one line (such as a directory path), and you have NirCMD, thn you can get this line into a variable with a single line of code. But at least there are several available options, as the answers have shown. – TechHorse Jan 02 '22 at 04:11
0

Is nircmd.exe (a) on your PATH, OR (b) in the same folder where your command window is, AND (c) not blocked by antivirus app you may have? I just copied this text (from your question, in my web browser) to the clipboard:

nircmd.exe consolewrite ~$clipboard$

Then I opened a cmd window and right clicked at the prompt (to paste the text of the command) and hit the Enter key, and nircmd gave it back as expected.

C:\Users\Mike>nircmd.exe consolewrite ~$clipboard$
nircmd.exe consolewrite ~$clipboard$
C:\Users\Mike>

I have nircmd.exe in a folder called c:\utils\ which is on my PATH.

Also this worked too (you know you use single percent signs for FOR metavariables at the prompt and double them in a batch script?)

C:\Users\Mike>for /f "delims=" %A in ('nircmd.exe consolewrite ~$clipboard$') do @echo %A
nircmd.exe consolewrite ~$clipboard$

C:\Users\Mike>.

Finally I created this batch and saved it as nirtest.bat (the echo. line is because nircmd does not paste a line feed/carriage return)

@echo off
echo 1
nircmd.exe consolewrite ~$clipboard$
echo.
echo 2
for /f "delims=" %%A in ('nircmd.exe consolewrite ~$clipboard$') do (
    echo Clipboard: %%A
)

Result:

C:\Users\Mike>nirtest.bat
1
some text in the clipboard
2
Clipboard: some text in the clipboard
Michael Harvey
  • 1,867
  • 14
  • 10
  • I tried your batch file code and while I got the last line printed on the screen, I just had a blank line between 1 & 2. Must be just a quirk of my system that the consolewrite command won't print to the screen on it's own. But as said elsewhere, that wasn't my priority. Getting the clipboard text into a variable was. Now done. – TechHorse Jan 01 '22 at 16:27
0

The following line will use nircmd.exe to save the text on the clipboard into the variable varCB.

    FOR /F "tokens=* USEBACKQ" %%F IN (`nircmd.exe consolewrite ~$clipboard$`) DO (SET varCB=%%F)

(This assumes a single line of text on the clipboard. If your clipboard text has multiple lines see the alternate code in the OP's UPDATE 2.

TechHorse
  • 269
  • 2
  • 13
  • You will only have the last line saved in variable `varCB` – Io-oI Jan 01 '22 at 18:00
  • You are right. See UPDATE 2 in the first post for code applicable for when the clipboard text has multiple lines. – TechHorse Jan 01 '22 at 19:27
  • Not sure what you mean. If I copy six lines of text, with lines 1,3 & 5 blank, then the code gives me empty variables for varCB1, varCB3 & varCB5. – TechHorse Jan 02 '22 at 03:47
0
SET "_NirCmd=D:\_NirSoft\nircmd-x64\nircmd.exe"
%_NirCmd% clipboard writefile F:\_Clip.txt
SET /P _VVV=<F:\_Clip.txt & DEL F:\_Clip.txt