azure函数发布到日志分析的Powershell脚本



我正在尝试编写一个azure函数,该函数将数据发布到特定的表,例如(Table_CL)内的日志分析工作空间。我正在运行错误。

Install-Module -Name Az.OperationalInsights -Scope CurrentUser -Force
$logAnalyticsClient = Get-AzOperationalInsightsWorkspace -ResourceGroupName "rg-name" -Name "log-analytics-wsp"

$WorkspaceId = "/subscriptions/subscriptionID/resourceGroups/rg-name/providers/Microsoft.OperationalInsights/workspaces/log-analytics-wsp"
$SharedKey = "some-value"
$CustomTableName = "Table_CL"

# Obtain an authentication token
$tenantId = 'some value'
$clientId = 'value of Function App identity client IOD'
$Uri = "https://log-analytics-wsp.ods.opinsights.azure.com/api/logs?api-version=2016-04-01"

$Body = @{
"EventId" = $eventGridEvent.id;
"eventType" = $eventGridEvent.eventType;
"subject" = $eventGridEvent.subject;
"TimeGenerated" = [datetime]$eventGridEvent.eventTime;
"data" = (ConvertTo-Json -InputObject $eventGridEvent.data);
"dataVersion" = $eventGridEventvent.dataVersion;
"metadataVersion" = $eventGridEvent.metadataVersion;
}
$signature = $SharedKey + (get-date -uformat '%a, %d %b %Y %H:%M:%S ')
$hex = ""
foreach ($byte in $signature) {
$hex += "{0:x2}" -f $byte
}
$Signature = $hex


$Headers = @{
"Content-Type" = "application/json"
"Log-Type" = $CustomTableName
"Authorization" = $Signature
}

# Use the authentication token to send a request to the Log Analytics API
Invoke-WebRequest -Uri $Uri -Method Post -Body $Body -Headers $Headers

我得到错误,可以有人请指导我如何张贴到日志分析使用powershell脚本的特定表。我得到以下错误:

2023-01-18T19:56:48Z   [Error]   ERROR: The format of value 'some-shared-key-value-==Wed, 18 Jan 2023 19:56:47 GMT' is invalid.
Exception             : 
Type       : System.FormatException
TargetSite : 
Name          : ParseValue
DeclaringType : System.Net.Http.Headers.HttpHeaderParser, System.Net.Http, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
MemberType    : Method
Module        : System.Net.Http.dll
Message    : The format of value 'some-shared-key-value-Wed, 18 Jan 2023 19:56:47 GMT' is invalid.
Source     : System.Net.Http
HResult    : -2146233033
StackTrace : 
at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
at System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, String value)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetRequest(Uri uri)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
at System.Management.Automation.Cmdlet.DoProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
CategoryInfo          : NotSpecified: (:) [Invoke-WebRequest], FormatException
FullyQualifiedErrorId : System.FormatException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
InvocationInfo        : 
MyCommand        : Invoke-WebRequest
ScriptLineNumber : 55
OffsetInLine     : 1
HistoryId        : 1
ScriptName       : C:homesitewwwrootEventGridTrigger1run.ps1
Line             : Invoke-WebRequest -Uri $Uri -Method Post -Body $Body -Headers $Headers

PositionMessage  : At C:homesitewwwrootEventGridTrigger1run.ps1:55 char:1
+ Invoke-WebRequest -Uri $Uri -Method Post -Body $Body -Headers $Header …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot     : C:homesitewwwrootEventGridTrigger1
PSCommandPath    : C:homesitewwwrootEventGridTrigger1run.ps1
InvocationName   : Invoke-WebRequest
CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, C:homesitewwwrootEventGridTrigger1run.ps1: line 55

有什么建议吗?我正在寻找方法张贴到日志分析工作空间特定表,任何帮助将是伟大的。


谢谢

我不得不使用azure docs中的以下API。这样就能很好地工作。只需插入值,post命令就可以在Azure Monitor中创建表。以下是文档的参考。

# Replace with your Workspace ID
$CustomerId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"  
# Replace with your Primary Key
$SharedKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Specify the name of the record type that you'll be creating
$LogType = "MyRecordType"
# Optional name of a field that includes the timestamp for the data. If the time field is not specified, Azure Monitor assumes the time is the message ingestion time
$TimeStampField = ""

# Create two records with the same set of properties to create
$json = @"
[{  "StringValue": "MyString1",
"NumberValue": 42,
"BooleanValue": true,
"DateValue": "2019-09-12T20:00:00.625Z",
"GUIDValue": "9909ED01-A74C-4874-8ABF-D2678E3AE23D"
},
{   "StringValue": "MyString2",
"NumberValue": 43,
"BooleanValue": false,
"DateValue": "2019-09-12T20:00:00.625Z",
"GUIDValue": "8809ED01-A74C-4874-8ABF-D2678E3AE23D"
}]
"@
# Create the function to create the authorization signature
Function Build-Signature ($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
}
# Create the function to create and post the request
Function Post-LogAnalyticsData($customerId, $sharedKey, $body, $logType)
{
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signature = Build-Signature `
-customerId $customerId `
-sharedKey $sharedKey `
-date $rfc1123date `
-contentLength $contentLength `
-method $method `
-contentType $contentType `
-resource $resource
$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
}
# Submit the data to the API endpoint
Post-LogAnalyticsData -customerId $customerId -sharedKey $sharedKey -body ([System.Text.Encoding]::UTF8.GetBytes($json)) -logType $logType

相关内容

  • 没有找到相关文章

最新更新