我编写了一些代码,试图从一个 Rest API 中获取一个值并将其发布到另一个。我将代码保存在 .ps1 文件中。如果我编辑它并运行它(或者只是将它复制并粘贴到一个空的 PowerShell 终端中),它会达到我的预期。但是,当我尝试直接运行相同的 .ps1 文件时,第二个 Invoke-RestMethod 出现错误。
不明白为什么我得到不同的结果并且错误消息没有给我很多线索。
我究竟做错了什么?
我正在使用的代码是(使用修改后的 API 密钥):
$encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($APIkey+":"))
$headers = @{"Content-Type" = "application/json"; "AUTHORIZATION" = "Basic $encoded"}
$APIkey = "123456789"
$metricId = "123"
$r = Invoke-RestMethod -Uri https://coinbase.com/api/v1/currencies/exchange_rates
$metric = [PSCustomObject]@{
value = [Math]::Round($r.btc_to_eur, 2)
}
$baseuri = "https://api.numerousapp.com/v1/metrics/$metricId/events"
$data = ConvertTo-Json $metric
Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
运行 .ps1 文件时收到的错误消息是:
Invoke-RestMethod : :
At C:\NumerousBitcoinEur.ps1:13 char:1
+ Invoke-RestMethod -Uri $baseuri -Body $data -Headers $headers -Method Post
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
我正在使用 PowerShell 4.0