将curl命令转换为Powershell

时间:2017-01-22 04:21:55

标签: json powershell

我可以使用curl来调用REST api

curl  -H 'Authorization: Bearer <token>' \
      -H 'Accept: application/json' \
      -H 'Content-Type: application/json' \
      -X POST \
      -d '<json>' \
      https://api.dnsimple.com/v2/1010/zones/example.com/records

并且json需要采用以下格式:

{
  "name": "",
  "type": "MX",
  "content": "mxa.example.com",
}

如何使用Invoke-WebRequest调用此API?我尝试以下操作(当然我在这里使用变量)当我打电话给我时我得到了错误400

$uri =  [string]::Format("https://api.dnsimple.com/v2/{0}/zones/{1}/records",$account,$domain)
$headers = @{}
$headers["Authorization"] = [string]::Format("Bearer {0}", $token)
$headers["Accept"] = "application/json"
$headers["Content-Type"] = "application/json"

$json = @{}
$json["name"] = $subdomain
$json["type"] = "A"
$json["content"] = $ip

Invoke-WebRequest -Uri $uri -Body $json -Headers $headers -Method Post

2 个答案:

答案 0 :(得分:3)

问题似乎是您将原始哈希表传递给-Body参数,而不是实际有效的JSON字符串。请使用ConvertTo-Json。此外,无需明确使用[string]::Format(),您可以使用-f运算符!

$uri = 'https://api.dnsimple.com/v2/{0}/zones/{1}/records' -f $account,$domain
$headers = @{
  Authorization = 'Bearer {0}' -f $token
  Accept        = 'application/json'
  Content-Type  = 'application/json'
}
$json = @{
  name    = "$subdomain"
  type    = "A"
  content = "$ip"
} |ConvertTo-Json
Invoke-WebRequest -Uri $uri -Body $json -Headers $headers -Method Post

答案 1 :(得分:-2)

我个人使用Invoke-RestMethod ......

参见 Get-Help Invoke-RestMethod -Examples

保存重新发明轮子。