0

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

1
  • well I get the same error as you when pasting in the console or when running from ISE. So I don't think the ps1 file as anything to do with it. Commented May 5, 2014 at 0:11

1 Answer 1

3

$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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! You're absolutely right, that was the problem and it worked in console because it was indeed already set. I tried a total clean restart of console and got the same problem when manually running. Can't believe the problem was that silly! Thanks for the tip with 'Set-StrictMode -Version Latest', didn't know about that one and looks very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.