如何在 PowerShell 窗口中传递卷曲请求中的标头

Gum*_*ert 3 powershell curl http

curl -X POST <myUrl> -H "authorization: Bearer <valid token>"
Run Code Online (Sandbox Code Playgroud)

但是当我发送它时,我收到异常 - 无法绑定参数“标头”。无法将“System.String”类型的“authorization: Bearer”值转换为“System.Collections.IDictionary”类型

Mat*_*sen 7

curl是 Windows PowerShell 中 cmdlet 的别名Invoke-WebRequest

正如错误消息所示,-Headers该 cmdlet 的参数接受标头键值对的字典。

要传递Authorization标头,您需要执行以下操作:

Invoke-WebRequest -Uri "<uri goes here>" -Method Post -Headers @{ Authorization = 'Bearer ...' } -UseBasicParsing
Run Code Online (Sandbox Code Playgroud)

(请注意,我明确传递了该-UseBasicParsing开关 - 如果没有,Windows PowerShell 将尝试使用 Internet Explorer 的 DOM 渲染引擎解析任何 HTML 响应,这在大多数情况下可能不是您想要的)


如果您需要传递-名称中带有标记终止字符(例如 )的标头,请使用'引号限定键:

$headers = @{ 
  'Authorization' = 'Bearer ...'
  'Content-Type'  = 'application/json'
}

Invoke-WebRequest ... -Headers $headers
Run Code Online (Sandbox Code Playgroud)

如果标头顺序很重要,请确保声明字典文字[ordered]

$headers = [ordered]@{ 
  'Authorization' = 'Bearer ...'
  'Content-Type'  = 'application/json'
}
Run Code Online (Sandbox Code Playgroud)