|
| 1 | +function Get-ApplicationInsightsQuery { |
| 2 | + [CmdletBinding()] |
| 3 | + param ( |
| 4 | + [Parameter(Mandatory = $true)] |
| 5 | + [string]$Query |
| 6 | + ) |
| 7 | + |
| 8 | + if (!$env:APPLICATIONINSIGHTS_CONNECTION_STRING) { |
| 9 | + throw 'Application Insights not enabled for this environment.' |
| 10 | + } |
| 11 | + |
| 12 | + if ($env:MSI_SECRET) { |
| 13 | + Connect-AzAccount -Identity |
| 14 | + } |
| 15 | + |
| 16 | + $SubscriptionId = $env:WEBSITE_OWNER_NAME -split '\+' | Select-Object -First 1 |
| 17 | + if ($env:WEBSITE_SKU -ne 'FlexConsumption' -and $Owner -match '^(?<SubscriptionId>[^+]+)\+(?<RGName>[^-]+(?:-[^-]+)*?)(?:-[^-]+webspace(?:-Linux)?)?$') { |
| 18 | + $RGName = $Matches.RGName |
| 19 | + } else { |
| 20 | + $RGName = $env:WEBSITE_RESOURCE_GROUP |
| 21 | + } |
| 22 | + $AppInsightsName = $env:WEBSITE_SITE_NAME |
| 23 | + |
| 24 | + $Body = @{ |
| 25 | + 'query' = $Query |
| 26 | + 'options' = @{'truncationMaxSize' = 67108864 } |
| 27 | + 'maxRows' = 1001 |
| 28 | + 'workspaceFilters' = @{'regions' = @() } |
| 29 | + } | ConvertTo-Json -Depth 10 -Compress |
| 30 | + |
| 31 | + $AppInsightsQuery = 'subscriptions/{0}/resourceGroups/{1}/providers/microsoft.insights/components/{2}/query' -f $SubscriptionId, $RGName, $AppInsightsName |
| 32 | + |
| 33 | + $resource = 'https://api.loganalytics.io' |
| 34 | + $Token = Get-AzAccessToken -ResourceUrl $resource |
| 35 | + |
| 36 | + $headerParams = @{'Authorization' = "Bearer $($Token.Token)" } |
| 37 | + $logAnalyticsBaseURI = 'https://api.loganalytics.io/v1' |
| 38 | + |
| 39 | + $result = Invoke-RestMethod -Method POST -Uri "$($logAnalyticsBaseURI)/$AppInsightsQuery" -Headers $headerParams -Body $Body -ContentType 'application/json' -ErrorAction Stop |
| 40 | + |
| 41 | + # Format Result to PSObject |
| 42 | + $headerRow = $null |
| 43 | + $headerRow = $result.tables.columns | Select-Object name |
| 44 | + $columnsCount = $headerRow.Count |
| 45 | + $logData = foreach ($row in $result.tables.rows) { |
| 46 | + $data = New-Object PSObject |
| 47 | + for ($i = 0; $i -lt $columnsCount; $i++) { |
| 48 | + $data | Add-Member -MemberType NoteProperty -Name $headerRow[$i].name -Value $row[$i] |
| 49 | + } |
| 50 | + $data |
| 51 | + } |
| 52 | + |
| 53 | + return $logData |
| 54 | +} |
0 commit comments