Skip to main content

Write custom logs via PowerShell

using namespace System.Net

# Input bindings are passed in via param block.
param(Request,TriggerMetadata)

# Interact with query parameters or the body of the request.
LogContent=Request.Body.LogContent
LogType=Request.Body.LogType

Function Build-Signature (customerId,sharedKey, date,contentLength, method,contentType, $resource){
    xHeaders="xmsdate:"+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=SharedKey0:1fcustomerId,$encodedHash
    return $authorization
}
 
Function Post-LogAnalyticsData (customerId,sharedKey, body,logType){
    $method = "POST"
    $contentType = "application/json"
    $resource = "/api/logs"
    $rfc1123date = ([DateTime]::UtcNow).ToString("r")
    contentLength=body.Length
    signature=BuildSignaturecustomerIdcustomerId -sharedKey sharedKeydaterfc1123date -contentLength contentLengthmethodmethod -contentType contentTyperesourceresource
   
    uri="https://"+customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
 
    $headers = @{
        "Authorization" = $signature;
        "Log-Type" = $logType;
        "x-ms-date" = $rfc1123date;
    }
 
    response=InvokeWebRequestUriuri -Method methodContentTypecontentType -Headers headersBodybody -UseBasicParsing
    return $response.StatusCode
}

$customerId = "06637cbc-c2ea-4093-acc8-fff2aac4fc6c"
$sharedKey = "ap7wS+3ec1DLA/2X/0BDiG7ojrAi9U3EI16o3VhrGeH74KWwrtUmVB5eS9V0vQPWTBLXmU9ZGQy8n1AInChkpw=="
$LogType = "ADDCNetlogonLogs"

$Properties = [Ordered] @{
    "ComputerName"     = $env:computername
    "User"             = $env:Username
}

CustomLogs=NewObjectTypeName"PSObject"PropertyProperties | ConvertTo-JSON -Depth 10


#Submit the data to the API endpoint
$params = @{
    CustomerId = $customerId
    SharedKey  = $sharedKey
    Body       = ([System.Text.Encoding]::UTF8.GetBytes($CustomLogs))
    LogType    = $LogType
}
$LogResponse = Post-LogAnalyticsData @params
$LogResponse