使用cmd将代码复制到剪贴板的问题

Problem with copying code to clipboard using cmd

这是代码

echo https://www.bing.com/search?PC=U523&q=%random%&pglt=129&FORM=ANNTA1&DAF0=1|clip

代码随机复制Microsoft Edge搜索link,使用%random%工具和clip工具将link复制到剪贴板

问题是,当我将代码放入 cmd 时,我收到此消息

https://www.bing.com/search?PC=U523
'q' is not recognized as an internal or external command,
operable program or batch file.
'pglt' is not recognized as an internal or external command,
operable program or batch file.
'FORM' is not recognized as an internal or external command,
operable program or batch file.
'DAF0' is not recognized as an internal or external command,
operable program or batch file.

代码中的主要问题是存在构成 command concatenation operators.

的符号 &

通常 escaping special characters (like ^&) is enough, but in this situation a pipe | is involved, which instantiates new cmd.exe 实例用于任何一方 1,然后接收未转义的字符。为此,需要建立double-escaping,像这样:

echo https://www.bing.com/search?PC=U523^^^&q=%random%^^^&pglt=129^^^&FORM=ANNTA1^^^&DAF0=1| clip

然而,根据是否涉及管道来编写转义序列是非常讨厌的,但是有一个不错的选择,即 delayed variable expansion。为此,字符串首先显然需要分配给一个变量:

rem // Store string to variable; use quoted `set` syntax to protect special characters:
set "URL=https://www.bing.com/search?PC=U523&q=%random%&pglt=129&FORM=ANNTA1&DAF0=1"
rem // Explicitly instantiate a new `cmd.exe` instance with delayed expansion enabled:
cmd /V:ON /D /C echo(!URL!| clip

1) 没有为只包含纯外部命令的管道的每一侧创建新实例(如 clip.exe)。