首页 > 解决方案 > 如何在批处理文件的 powershell 命令中包含与号?

问题描述

我正在尝试通过批处理文件下载 Google 表格。这有效:

powershell -Command "Invoke-WebRequest https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv -OutFile output.tsv"

当我通过添加 &gid=1234 指定我想要的工作表/选项卡时,这会中断:

powershell -Command "Invoke-WebRequest https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234 -OutFile output.tsv"

错误是:

不允许使用与号 (&) 字符。& 运算符保留供将来使用;用双引号 ("&") 将 & 号括起来以将其作为字符串的一部分传递。

如何在不破坏 Command 参数的外部引号的情况下将 & 号括在引号中?

标签: powershellbatch-filegoogle-sheetsquoting

解决方案


嵌入在"..."传递给的字符串中的 URL 也powershell -Command必须被引用,因为未引用的 URL 对PowerShell &也具有特殊意义(尽管在 Windows PowerShell 中它目前仅保留以供将来使用;在 PowerShell Core中,它可以用于后定位运行命令作为后台工作)。

正如Olaf所建议的那样,最简单的选择是使用嵌入式'...'引用,因为chars. 不需要逃到里面。PowerShell 中的字符串是文字字符串,在这种情况下很好,因为 URL 不包含变量引用。'"..."'...'

powershell -Command "Invoke-WebRequest 'https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234' -OutFile output.tsv"

"..."如果字符串插值需要嵌入\"引用,请使用(sic) 转义嵌入的 ( ") 字符。(请注意,PowerShell 中,您需要使用`"or""代替):

powershell -Command "Invoke-WebRequest \"https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/export?exportFormat=tsv&gid=1234\" -OutFile output.tsv"

推荐阅读