Last active
January 17, 2020 20:00
-
-
Save darrenjrobinson/d3e63e565b9f62363b970b77be761477 to your computer and use it in GitHub Desktop.
Query Azure Log Analytics using PowerShell. Associated blog post https://blog.darrenjrobinson.com/sending-and-querying-custom-log-data-to-azure-monitor-logs/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$TenantId = 'yourAzureTenantID' | |
$loggingClientID = 'AzureADLoggingAppClientID' | |
$loggingSecret = 'AzureADLoggingAppClientSecret' | |
$logAnalyticsWorkspace = 'yourLogAnalyticsWorkspaceID' | |
$customLogName = "ourAppCustomLogs_CL" | |
# Get Access Token for Log Analytics to allow KQL Queries to get last ingested events in Custom Logs | |
$loginURL = "https://login.microsoftonline.com/$TenantId/oauth2/token" | |
$resource = "https://api.loganalytics.io" | |
$authbody = @{grant_type = "client_credentials"; resource = $resource; client_id = $loggingClientID; client_secret = $loggingSecret } | |
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL -Body $authbody | |
$headerParams = @{'Authorization' = "$($oauth.token_type) $($oauth.access_token)" } | |
$logAnalyticsBaseURI = "https://api.loganalytics.io/v1/workspaces" | |
# Get last 2 records from Log Analytics Data ourAppCustomLogs | |
$result = invoke-RestMethod -method Get -uri "$($logAnalyticsBaseURI)/$($logAnalyticsWorkspace)/query?query=$($customLogName) | sample 2 | sort by TimeGenerated" -Headers $headerParams | |
# Format Result to PSObject | |
$headerRow = $null | |
$headerRow = $result.tables.columns | Select-Object name | |
$columnsCount = $headerRow.Count | |
$logData = @() | |
foreach ($row in $result.tables.rows) { | |
$data = new-object PSObject | |
for ($i = 0; $i -lt $columnsCount; $i++) { | |
$data | add-member -membertype NoteProperty -name $headerRow[$i].name -value $row[$i] | |
} | |
$logData += $data | |
$data = $null | |
} | |
[string]$lastEntry = $logData[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment