Search code examples
azurepowershellazure-application-insights

How to run an Azure Log Analytics query from a Powershell script non interactively?


Given:

  • I have an Azure account (MSDN benefits).
  • I have a console application sending custom AppInsights metrics to my AppInsights workspace.

I would like to query these metrics from a PowerShell script.

I did try to find a solution by googling for it - no success. Not that there is no posts about the subject - I am just unable to make it work following these posts.

The gist of the problem is how to do it without user interaction.


Solution

  • You can use Azure Application Insights REST API to get these metrics.

    Steps as below:

    step 1: Get the Application ID and an API key.

    Nav to your application insights -> API Access, see the screenshot(Please remember, when the api key is generated, write it down): enter image description here

    step 2: In powershell, input the following cmdlet(the example code for fetching customEvents count):

    Invoke-WebRequest -Uri https://api.applicationinsights.io/v1/apps/your_application_id/metrics/customEvents/cou
    nt?timespan=P20D -Headers @{"accept"="application/json"; "x-api-key"="your_api_key"}
    

    Result as below: enter image description here

    The details of the REST API is here.