【发布时间】:2014-05-04 09:48:03
【问题描述】:
我编写了一些代码,试图从一个 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
【问题讨论】:
-
我在控制台中粘贴或从 ISE 运行时遇到与您相同的错误。所以我不认为 ps1 文件与它有任何关系。