Pergunta

I wrote some code which tries to Get a value from one Rest API and post it to another. I have the code saves in a .ps1 file. If I edit it and run it (or just copy and paste it into an empty PowerShell terminal) it does what I expect. However when I try to run the same .ps1 file directly I get an error on the 2nd Invoke-RestMethod.

Don't understand why I'm getting a different result and the error message not giving me many clues.

What am I doing wrong?

The code I am using is (with modified API key):

$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

And the error message I get when running the .ps1 file is:

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

I'm using PowerShell 4.0

Foi útil?

Solução

$APIkey is being set after it is being used, which must be wrong. It probably works in the console because $APIkey happens to already be set.

If you like (I think it's a good idea), you can add the following to the top of your scripts to catch errors like this one.

Set-StrictMode -Version Latest
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top