【问题标题】:PowerShell Invoke-WebRequest error with Go Daddy APIGo Daddy API 的 PowerShell Invoke-WebRequest 错误
【发布时间】:2019-04-05 20:05:06
【问题描述】:

按照许多其他人建议的脚本(from here) 工作正常,我遇到了一个超出我理解能力的错误。我是 Power Shell 的新手到中级,刚开始接触 API。

脚本是:

$domain = 'example.com'                    # your domain
$name = 'xyz'                              # name of the A record to update
$key = 'myKey                              # key for godaddy developer API
$secret = 'mySecret'                       # Secret for godday developer API

$headers = @{}
$headers["Authorization"] = 'sso-key ' + $key + ':' + $secret
$result = Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method get -headers $headers
$content = ConvertFrom-Json $result.content
$dnsIp = $content.data

# Get public ip address
$currentIp = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip

# THE CODE WORKS FINE UP TO HERE

if ( $currentIp -ne $dnsIp) {
    $Request = @{ttl=3600;data=$currentIp }
    $JSON = Convertto-Json $request

# THE FOLLOWING LINE FAILS WITH THE ERROR NOTED BELOW

    Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method put -headers $headers -Body $json -ContentType "application/json"
} 

最终的 Invoke-WebRequest 返回以下错误:

Invoke-WebRequest : {"code":"INVALID_BODY","fields":[{"code":"UNEXPECTED_TYPE","message":"is not a array","path":"records"}],"message":"Request body doesn't fulfill schema, see details in `fields`"}
At C:\tfsCode\tfs\api.ps1:25 char:5
+     Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/reco ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

the Get API is herethe Put API is here 的 Go Daddy 参考页面。

【问题讨论】:

    标签: api powershell godaddy-api


    【解决方案1】:

    PUT API 文档说它期望 body 是一个数组。这也是错误消息所说的。尝试更改此行:

    $Request = @{ttl=3600;data=$currentIp }
    

    $Request = @(@{ttl=3600;data=$currentIp })
    

    @() 在 PowerShell 中创建一个数组,当转换为 JSON 时它仍然是一个数组

    @{} 在 PowerShell 中创建一个哈希表,转换为 JSON 后它将是一个对象

    【讨论】:

    • 略短:$Request = ,@{ttl=3600;data=$currentIp } (+1)
    • 这很微妙,我非常感谢您的帮助。工作完美。这让我想知道原始代码是如何为其他人运行的。
    猜你喜欢
    • 2012-07-26
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多