Invoke-LogAnalyticsQuery.ps1

function Get-Headers {
    param (
        [parameter()][string] $AccessToken,
        [parameter()][switch] $IncludeStatistics,
        [parameter()][switch] $IncludeRender,
        [parameter()][int] $ServerTimeout
    )
    $preferString = "response-v1=true"
    if ($IncludeStatistics) {
        $preferString += ",include-statistics=true"
    }
    if ($IncludeRender) {
        $preferString += ",include-render=true"
    }
    if ($null -ne $ServerTimeout) {
        $preferString += ",wait=$ServerTimeout"
    }
    $headers = @{
        "Authorization" = "Bearer $accessToken";
        "prefer" = $preferString;
        "x-ms-app" = "LogAnalyticsQuery.psm1";
        "x-ms-client-request-id" = [Guid]::NewGuid().ToString();
    }
    $headers
}

function Get-ArmHost {
    param(
        [parameter()][string] $environment
    )
    switch ($environment) {
        ""      {$armHost = "management.azure.com"}
        "aimon" {$armHost = "management.azure.com"}
        "int"   {$armHost = "api-dogfood.resources.windows-int.net"}
    }
    $armHost
}

function Build-Uri {
    param (
        [parameter()][string] $armHost,
        [parameter()][string] $subscriptionId,
        [parameter()][string] $resourceGroup,
        [parameter()][string] $workspaceName,
        [parameter()][string] $queryParams
    )
    "https://$armHost/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/" + `
        "microsoft.operationalinsights/workspaces/$workspaceName/api/query?$queryParamString"
}

function Get-AccessToken {
    $azureCmdlet = get-command -Name Get-AzureRMContext -ErrorAction SilentlyContinue
    if ($null -eq $azureCmdlet) {
        $null = Import-Module AzureRM -ErrorAction Stop;
    }
    $AzureContext = & "Get-AzureRmContext" -ErrorAction Stop;
    $authenticationFactory = New-Object -TypeName Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory
    if ((Get-Variable -Name PSEdition -ErrorAction Ignore) -and ('Core' -eq $PSEdition)) {
        [Action[string]]$stringAction = {param($s)}
        $serviceCredentials = $authenticationFactory.GetServiceClientCredentials($AzureContext, $stringAction)
    } 
    else {
        $serviceCredentials = $authenticationFactory.GetServiceClientCredentials($AzureContext)
    }

    # We can't get a token directly from the service credentials. Instead, we need to make a dummy message which we will ask
    # the serviceCredentials to add an auth token to, then we can take the token from this message.
    $message = New-Object System.Net.Http.HttpRequestMessage -ArgumentList @([System.Net.Http.HttpMethod]::Get, "http://foobar/")
    $cancellationToken = New-Object System.Threading.CancellationToken
    $null = $serviceCredentials.ProcessHttpRequestAsync($message, $cancellationToken).GetAwaiter().GetResult()
    $accessToken = $message.Headers.GetValues("Authorization").Split(" ")[1] # This comes out in the form "Bearer <token>"

    $accessToken
}

function New-ObjectView {
    param (
        [parameter()] $data
    )
    # Find the number of entries we'll need in this array
    $count = 0
    foreach ($table in $data.Tables) {
        $count += $table.Rows.Count
    }
    $objectView = New-Object object[] $count
    $i = 0;
    foreach ($table in $data.Tables) {
        foreach ($row in $table.Rows) {
            # Create a dictionary of properties
            $properties = @{}
            for ($columnNum=0; $columnNum -lt $table.Columns.Count; $columnNum++) {
                $properties[$table.Columns[$columnNum].name] = $row[$columnNum]
            }
            # Then create a PSObject from it. This seems to be *much* faster than using Add-Member
            $objectView[$i] = (New-Object PSObject -Property $properties)
            $null = $i++
        }
    }
    $objectView
}

function Invoke-DsLogAnalyticsQuery {
    <#
    .DESCRIPTION
        Invokes a query against the Log Analtyics Query API.
 
    .PARAMETER WorkspaceName
        The name of the Workspace to query against.
 
    .PARAMETER SubscriptionId
        The ID of the Subscription this Workspace belongs to.
 
    .PARAMETER ResourceGroup
        The name of the Resource Group this Workspace belongs to.
 
    .PARAMETER Query
        The query to execute.
 
    .PARAMETER Timespan
        The timespan to execute the query against. This should be an ISO 8601 timespan.
 
    .PARAMETER IncludeTabularView
        If specified, the raw tabular view from the API will be included in the response.
 
    .PARAMETER IncludeStatistics
        If specified, query statistics will be included in the response.
 
    .PARAMETER IncludeRender
        If specified, rendering statistics will be included (useful when querying metrics).
 
    .PARAMETER ServerTimeout
        Specifies the amount of time (in seconds) for the server to wait while executing the query.
 
    .PARAMETER Environment
        Internal use only.
 
    .EXAMPLE
        Invoke-DsLogAnaltyicsQuery -WorkspaceName "ws123" `
            -SubscriptionId 12345678-abcd-efgh-4321-1234abcd5678 `
            -ResourceGroup "my-resourcegroup" `
            -Query "WaaSUpdateStatus | where NeedAttentionStatus==`"Missing multiple security updates`" | render table" `
            -CreateObjectView
 
    .NOTES
        NAME: Invoke-DsLogAnaltyicsQuery
        Adapted heavily from Eli Shlomo example at https://www.eshlomo.us/query-azure-log-analytics-data-with-powershell/
 
    .LINK
        https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Invoke-DsLogAnalyticsQuery.md
    #>

    [CmdletBinding()]
    param (
        [parameter(Mandatory)][string] $WorkspaceName,
        [parameter(Mandatory)][guid] $SubscriptionId,
        [parameter(Mandatory)][string] $ResourceGroup,
        [parameter(Mandatory)][string] $Query,
        [parameter()][string] $Timespan,
        [parameter()][switch] $IncludeTabularView,
        [parameter()][switch] $IncludeStatistics,
        [parameter()][switch] $IncludeRender,
        [parameter()][int] $ServerTimeout,
        [parameter()][string][ValidateSet("", "int", "aimon")] $Environment = ""
    )
    $apiVersion = "2017-01-01-preview"

    $ErrorActionPreference = "Stop"

    $accessToken = Get-AccessToken
    $armhost = Get-ArmHost $environment
    $queryParams = @("api-version=$apiVersion")
    $queryParamString = [string]::Join("&", $queryParams)
    $uri = Build-Uri $armHost $subscriptionId $resourceGroup $workspaceName $queryParamString

    $body = @{
        "query" = $query;
        "timespan" = $Timespan
    } | ConvertTo-Json

    $headers = Get-Headers $accessToken -IncludeStatistics:$IncludeStatistics -IncludeRender:$IncludeRender -ServerTimeout $ServerTimeout
    $response = Invoke-WebRequest -UseBasicParsing -Uri $uri -Body $body -ContentType "application/json" -Headers $headers -Method Post

    if ($response.StatusCode -ne 200 -and $response.StatusCode -ne 204) {
        $statusCode = $response.StatusCode
        $reasonPhrase = $response.StatusDescription
        $message = $response.Content
        throw "Failed to execute query.`nStatus Code: $statusCode`nReason: $reasonPhrase`nMessage: $message"
    }

    $data = $response.Content | ConvertFrom-Json

    $result = New-Object PSObject
    $result | Add-Member -MemberType NoteProperty -Name Response -Value $response

    # In this case, we only need the response member set and we can bail out
    if ($response.StatusCode -eq 204) {
        $result
        return
    }

    $objectView = New-ObjectView $data

    $result | Add-Member -MemberType NoteProperty -Name Results -Value $objectView

    if ($IncludeTabularView) {
        $result | Add-Member -MemberType NoteProperty -Name Tables -Value $data.tables
    }

    if ($IncludeStatistics) {
        $result | Add-Member -MemberType NoteProperty -Name Statistics -Value $data.statistics
    }

    if ($IncludeRender) {
        $result | Add-Member -MemberType NoteProperty -Name Render -Value $data.render
    }
    $result
}