Skip to content

Instantly share code, notes, and snippets.

@markwragg
Created April 25, 2020 12:42
Show Gist options
  • Save markwragg/9fc8ce402fa4738e29133455866fc387 to your computer and use it in GitHub Desktop.
Save markwragg/9fc8ce402fa4738e29133455866fc387 to your computer and use it in GitHub Desktop.
A PowerShell function for querying one or more AppInsights accounts (or all AppInsights accounts under a subscription once logged in) to get the daily cap setting and previous 24 hours of usage
Function Get-AppInsightsUsage {
Param(
# Optional: One or more AppInsights resource names
[string[]]
$Name
)
$AppInsights = Get-AzApplicationInsights
If ($Name) { $AppInsights = $AppInsights | Where-Object { $_.Name -in $Name } }
ForEach ($AI in $AppInsights) {
$DailyCap = Set-AzureRmApplicationInsightsDailyCap -ResourceGroupName $AI.ResourceGroupName -Name $AI.Name
$Permissions = @('ReadTelemetry', 'WriteAnnotations')
$APIKey = New-AzApplicationInsightsApiKey -ResourceGroupName $AI.ResourceGroupName -Name $AI.Name -Permissions $Permissions -Description 'GetAppInsightsUsageKey'
$AppId = $AI.AppId
$Headers = @{
'X-Api-Key' = $APIKey.ApiKey
'Content-Type' = 'application/json'
}
$Query = 'systemEvents
| where timestamp >= ago(24h)
| where type == "Billing"
| extend BillingTelemetryType = tostring(dimensions["BillingTelemetryType"])
| extend BillingTelemetrySizeInBytes = todouble(measurements["BillingTelemetrySize"])
| summarize sum(BillingTelemetrySizeInBytes)'
$EscapedQuery = [uri]::EscapeUriString("?query=$Query")
$Result = Invoke-RestMethod -uri "https://api.applicationinsights.io/v1/apps/$AppId/query$EscapedQuery" -Headers $Headers
$Usage = [Math]::Round($Result.tables.rows[0] / 1GB, 2)
Remove-AzApplicationInsightsApiKey -ApiKeyId $APIKey.Id -ResourceGroupName $AI.ResourceGroupName -Name $AI.Name
[pscustomobject]@{
Name = $AI.Name
ResourceGroup = $AI.ResourceGroupName
DailyCap = $DailyCap.Cap
Usage = $Usage
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment