Invoke-LogAnalyticsQuery.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
}