This example uses PowerShell to write a JSON data file into Log Analytics (and Microsoft Sentinel).
Note this uses a second function "Get-Signature" for signing the data being written to the workspace. That function can be viewed here:
PowerShell Function - Create Signature for writing Log Analytics data | Laurie Rhodes' Info
<#
Function: Write-LogAnalyticsData
Purpose: To write data (JSON format) to a Log Analyutics Workspace.
Parameters: -WorkspaceId = Log Analytics Workspace GUID
-sharedKey = Log Analytics shared key (either primary or secondary)
-body = The data submitted for Log Analytics (JSON format)
-logType = The name of the Log within a workspace to write to.
Example:
Write-LogAnalyticsData `
-WorkspaceId "ed4ef888-5466-401c-b77a-6f9cd7cc6815" `
-sharedKey $SharedKey `
-body ([System.Text.Encoding]::UTF8.GetBytes(($PolDefArray | convertto-json) )) `
-logType "MySystemLogs" `
#>
Function Write-LogAnalyticsData(){
param (
[Parameter(Mandatory = $true)] [string] $WorkspaceId ,
[Parameter(Mandatory = $true)] [string] $sharedKey ,
[Parameter(Mandatory = $true)] [string] $body ,
[Parameter(Mandatory = $true)] [string] $logType,
[Parameter(Mandatory = $false)] [string] $TimeStampField=""
)
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signature = Get-Signature `
-WorkspaceId $WorkspaceId `
-sharedKey $sharedKey `
-date $rfc1123date `
-contentLength $contentLength `
-method $method `
-contentType $contentType `
-resource $resource
$uri = "https://" + $WorkspaceId + ".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 -TimeoutSec 0
if (!($response.StatusCode -eq "200")){ throw "Failed Authorization status code - $( $response.StatusCode ) " }
return $response.StatusCode
}
- Log in to post comments