【问题标题】:How to escape @ within a string in PowerShell?如何在PowerShell中的字符串中转义@?
【发布时间】:2021-09-28 21:57:12
【问题描述】:

我正在尝试通过 PowerShell 中的 cURL 发送 HTML 请求。有问题的代码:

$command = 'curl -d @request.txt -o testoutput.xml -X "POST" -H @header.txt -u "username:password" "URL"'
Invoke-Expression $command

HTML 正文 (-d) 和标头 (-H) 需要从文件中读取,因此文件名前有 @。

为了使其正常工作,我需要转义 @ 以便 PowerShell 不会将其解释为 splat 运算符 - 这是我的问题,到目前为止我没有尝试过任何工作:

  • 用单引号括起来
  • 这里是文档 (@" "@)
  • 这里是字符串(@''@)
  • 使用带占位符的字符串模板 ("{0}request.txt" -f "@")
  • Unicode 转义(“`u{0040}request.txt”)

如何正确转义 @?还是我完全走错了路? (抱歉,我是 PowerShell 新手)

【问题讨论】:

  • 使用 --%: curl --% -d @request.txt -o testoutput.xml -X "POST" -H @header.txt -u "username:password" "URL" - 这将阻止 PowerShell 解析器尝试评估其后的任何内容

标签: powershell curl escaping


【解决方案1】:

Invoke-Expression (iex) should generally be avoided;绝对是don't use it to invoke an external program or PowerShell script

因此:

  • 直接调用curl
  • quote PowerShell 元字符,例如@(完整列表请参见this answer)- 单独,@987654330 @(例如,`@),或将整个参数括在引号中('...'"...",视情况而定)。
curl -d `@request.txt -o testoutput.xml -X "POST" -H @header.txt -u "username:password" "URL"

至于你尝试了什么

关于Invoke-Expression 使用的主要问题是安全之一:不必要地执行可能注入传递给它的字符串中的(附加)命令。

功能而言,Invoke-Expression 不仅需要定期调用外部程序,它还可能造成引用问题

但是,鉴于您将 '...' 字符串传递给 Invoke-Expression,将 @ 引用为 `@ 会起作用,如下面的简单示例所示:

# OK, but generally do NOT do this.
Invoke-Expression 'Write-Output `@'

如果您使用了"..." 字符串,那么` 会被这样一个expandable string 的预先解析“吃掉”,基于概念性about_Quoting_Rules 帮助主题中解释的转义规则:

# BREAKS, because the ` is stripped before Invoke-Expression sees it.
Invoke-Expression "Write-Output `@"

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2015-10-26
    • 2010-09-23
    相关资源
    最近更新 更多