Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Post an object to Log Analytics with PowerShell
# Adapted from https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-data-collector-api
Function Get-LogAnalyticsSignature {
[cmdletbinding()]
Param (
$customerId,
$sharedKey,
$date,
$contentLength,
$method,
$contentType,
$resource
)
$xHeaders = "x-ms-date:" + $date
$stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource
$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
$keyBytes = [Convert]::FromBase64String($sharedKey)
$sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash
return $authorization
}
Function Export-LogAnalytics {
[cmdletbinding()]
Param(
$customerId,
$sharedKey,
$object,
$logType,
$TimeStampField
)
$bodyAsJson = ConvertTo-Json $object
$body = [System.Text.Encoding]::UTF8.GetBytes($bodyAsJson)
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signatureArguments = @{
CustomerId = $customerId
SharedKey = $sharedKey
Date = $rfc1123date
ContentLength = $contentLength
Method = $method
ContentType = $contentType
Resource = $resource
}
$signature = Get-LogAnalyticsSignature @signatureArguments
$uri = "https://" + $customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
$headers = @{
"Authorization" = $signature;
"Log-Type" = $logType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
}
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
return $response.StatusCode
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.