In a previous post I wrote about using Powershell to work with the New Relic monitoring service API, which gives you the ability to query performance metrics it gathers about your application. Once you have this data, it is easy to do whatever you want with it; store it in a database, send a formatted report in email, etc. In the first post I included snippets of script code and instructions on how to connect to the API, pass the API key, and get a summary of metric data using the built-in XML parsing capabilities in Powershell.

What if you want more than just a summary? What if you also use the sever monitoring features and want data about those metrics too? You can pull just about any New Relic metric data you want, and that’s the subject of this second post.

First, I retrieved all of the metric names for a server. You can also specify a specific agent for the application monitoring functionality;

The above will return all the metric names and write them to a text file. Once you know all of the names, it’s time to start building the code to get to the data. In this example we’ll use the server monitoring metric System/CPU/System/percent to get an XML formatted response:

Armed with this info, I was then able to build a call that got the average value of the CPU for the server in the last 24 hours. I found that the API expects a very specific timestamp within the metric URL so I used get-date to format it the way I wanted it and set the start time to 24 hours ago. There may be a more elegant way to insert the date, but this is what I came up with.

1

2

3

4

5

6

7

8

9

$endDate=get-date-formatyyyy-MM-dd

$endTime=get-date-formatHH:mm

$startTime=(get-date).AddHours(-24)

$hour=$startTime.Hour

$min=$startTime.Minute

$year=$startTime.Year

$month=$startTime.Month

$day=$startTime.Day

Then I built a variable containing the string in the proper format. The API will return errors if it isn’t.

$servCPU will now hold the raw value, you can round it up or leave it as is. You can use this method for all of the metrics available as well as the other fields in the CPU data. New Relic has more documentation for their API at newrelic.com