Skip to content

Instantly share code, notes, and snippets.

@darrenjrobinson
Last active January 17, 2020 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjrobinson/d3e63e565b9f62363b970b77be761477 to your computer and use it in GitHub Desktop.
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/
$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