The New Relic API and Powershell

I’ve used the awesome performance monitoring tool New Relic to gather diagnostics and other stats for applications. I thought it would be a really cool idea to get some of the metrics using the New Relic API, but there wasn’t much information on how to do it with Powershell. This is relatively simple though, and can be done in different ways depending on the version you use. The code I’m using is 2.0 but I’ll include some snippets of 3.0 equivalent.

The New Relic API is REST but requires authentication. Similar to other services, you will need to enable the API access for your account. This generates an API key you will need to authenticate. There is a good document of the API on Github @ http://newrelic.github.com/newrelic_api/

With this simple bit of code, you can get and parse the data returned by New Relic;

$APIkey = "YourAPIKeyHere"
$url = "APIURLHERE"

$webClient = new-object System.Net.WebClient
$webclient.Headers.Add("x-api-key",$APIkey)
$output = $WebClient.DownloadString($url).Replace("threshold-values","thresholdvalues")

Using the XML abilities baked into Powershell, I can now use the common dotted notation to get what I want. Also I’m doing a replace on the returned data to get rid of the hyphen in it, which trips Powershell up no matter what I did to try and escape it. I decided to circle back to that little problem later and just did the replace. Keep in mind this only applied to the summary metrics data that I wanted and may not be needed for some of the other API calls.

Here is an example of returning all the New Relic metric names. Here I am using the 3.0 auto foreach which automatically outputs all of the values. You will need a real loop in 2.0;

$output.thresholdvalues.threshold_value.name

With Powershell 3, you can also use the built in REST commands and it’s auto foreach to achieve the same results and more. I didn’t dive into that much because most of my production environments are using 2.0 but here’s a sample of how that would look;

$url = "https://api.newrelic.com/api/v1/accounts/acctNumberHere/applications/AppIDHere/threshold_values.xml"
$APIkey = "YourAPIKeyHere"

$headers = @{"x-api-key"="$APIkey"}
$results = invoke-RestMethod -Uri $url -Header $headers
Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *