Reading the Windows Clipboard from a Batch File

The hybrid batch/JScript pattern

The script below uses a single file that the Windows script host interprets twice: first as a batch file, then as JScript. The batch section calls cscript on itself, passing the file path (%~f0). The JScript section creates an htmlfile ActiveX object, reaches into parentWindow.clipboardData.getData('text'), and echoes the result back to stdout where the batch loop can capture it line by line.

@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'));

Implications for maintenance

The approach still works on supported Windows versions because cscript and the htmlfile COM object remain present. It avoids third-party utilities such as clip.exe or PowerShell, which can be convenient on locked-down endpoints. The trade-off is opacity: the dual-language file is harder to audit than a straight PowerShell one-liner (Get-Clipboard). If you control the execution environment, prefer PowerShell for readability; keep this pattern only when you must stay inside a pure .bat context.

Back to the blog index