【问题标题】:How to escape pipe character from PowerShell command line to pass into non-PowerShell command如何从 PowerShell 命令行转义管道字符以传递给非 PowerShell 命令
【发布时间】:2016-10-28 04:33:39
【问题描述】:

我在 PowerShell 控制台会话中,尝试从 PowerShell 命令行运行存在于 cwd 中的 Gradle 脚本。

Gradle 命令接受一个参数,该参数包括可以包含一个或多个管道字符的引号,我一生都无法弄清楚如何让 PowerShell 仅使用一行(或任意数量的行)来转义它,实际上 - 但我对多线解决方案不感兴趣)。

命令如下:

./gradlew theTask -PmyProperty="thisThing|thatThing|theOtherThing"

...产生此错误:

'thatThing' is not recognized as an internal or external command, operable program or batch file.

我已经尝试了所有这些变体,但都不起作用。有什么想法吗?

./gradlew theTask -PmyProperty="thisThing`|thatThing`|theOtherThing"
./gradlew theTask -PmyProperty=@"thisThing|thatThing|theOtherThing"
./gradlew theTask -PmyProperty="thisThing\|thatThing\|theOtherThing"
./gradlew theTask -PmyProperty="thisThing\\|thatThing\\|theOtherThing"
./gradlew theTask -PmyProperty="thisThing^|thatThing^|theOtherThing"

【问题讨论】:

  • 你试过^|吗?
  • @Jean-FrançoisFabre:是的。我会把它添加到列表中。我认为这是一个 DOS shell 转义字符
  • 对不起,那是猜测。然而,我已经尝试过这个 `echo theTask -PmyProperty="thisThing|thatThing|theOtherThing"`` 并且 echo 命令可以正常工作(Windows 10)。可以试试吗?
  • 是的,这回显了出现在“echo”之后的参数。但是,我需要它使用相同的参数运行 cwd 中的 gradle 脚本
  • 所以问题必须存在于 gradle 脚本中。您是否尝试过在脚本开头打印一些内容?

标签: shell powershell command-line escaping


【解决方案1】:

好吧,我发现:

首先按照我最初的建议这样调用您的脚本:

./gradlew theTask -PmyProperty="thisThing^|thatThing^|theOtherThing"

然后通过添加引号来修改您的 gradlew.bat 脚本:

set CMD_LINE_ARGS="%*"

问题是:现在必须在引号内调用 CMD_LINE_ARGS 否则会出现同样的错误。

所以我假设你的命令行参数不能是别的东西,我正在一个一个地处理每个参数

rem now remove the quotes or there will be too much quotes
set ARG1="%1"
rem protect or the pipe situation will occur
set ARG1=%ARG1:""=%
set ARG2="%2"
set ARG2=%ARG2:""=%
set ARG3="%3"
set ARG3=%ARG3:""=%

echo %ARG1% %ARG2% %ARG3%

输出是(对于我的模型命令):

theTask -PmyProperty "thisThing|thatThing|theOtherThing"

“=”已消失,因为它已将参数与 PowerShell 分开。如果您的命令具有标准参数解析,我想这不会成为问题。

根据需要添加任意数量的参数,但无论如何限制为 9 个。

【讨论】:

  • 不幸的是,对于命令行参数列表,我没有任何可以依赖的模式,它将有可变数量的参数,我不会提前知道哪个(如果有的话)参数可能需要转义
  • 我已经对所有参数应用了我的更改,应该会更好。
  • 感谢您的帮助 - 最终,解决方案在于 gradle 团队的 bug report,因为我不拥有脚本的开发。
【解决方案2】:

发现另一种可能性here。可以像这样使用单引号和双引号。不确定这是否有助于解决最初的问题,但它有助于解决我的问题。

'"thisThing|thatThing|theOtherThing"'

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2016-05-22
    • 2023-03-30
    • 2022-12-20
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2012-11-07
    相关资源
    最近更新 更多