Created
August 26, 2018 23:40
-
-
Save taddison/d49bd8c6f7fc1d45aa8e7b0906c180ae to your computer and use it in GitHub Desktop.
Post an object to Log Analytics with PowerShell
This file contains hidden or 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
| # 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