如何使用 Powershell 向 AppInsights 指标添加属性

问题描述 投票:0回答:1

我正在开发一个将指标发送到 Azure Application Insights 的 powershell 脚本。 我可以使用此代码发送度量样本,np 问题。

$telemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new()
$telemetryClient.TelemetryConfiguration.ConnectionString = 'InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/'

$Sample = [Microsoft.ApplicationInsights.DataContracts.MetricTelemetry]::new()
$Sample.Name = 'TotalAppRegs'
$Sample.Timestamp = $now
$Sample.Value = 100

$telemetryClient.TrackMetric($Sample)
$telemetryClient.Flush()

现在我想向 $Sample 添加一些属性,据我了解,这些属性将在 appinsights 中显示为自定义维度

$telemetryClient = [Microsoft.ApplicationInsights.TelemetryClient]::new()
$telemetryClient.TelemetryConfiguration.ConnectionString = 'InstrumentationKey=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/'

$Sample = [Microsoft.ApplicationInsights.DataContracts.MetricTelemetry]::new()
$Sample.Name = 'TotalAppRegs'
$Sample.Timestamp = $now
$Sample.Value = 100
$Sample.Properties.Add('key','value')

$telemetryClient.TrackMetric($Sample)
$telemetryClient.Flush()

我收到错误:MethodException:找不到“Add”的重载和参数计数:“2”。虽然定义指出:

PS: $Sample.Properties|gm add|fl       

TypeName   : System.Collections.Concurrent.ConcurrentDictionary`2[[System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral,
             PublicKeyToken=7cec85d7bea7798e]]
Name       : Add
MemberType : Method
Definition : void IDictionary[string,string].Add(string key, string value), void ICollection[KeyValuePair[string,string]].Add(System.Collections.Generic.KeyValuePair[string,string] item), void IDictionary.Add(System.Object key, System.Object value)

我在这里做错了什么?

azure powershell azure-application-insights
1个回答
0
投票

TrackMetric
函数有一个重载,它接受字典来设置customProperties(docs here)。下面的调用就可以解决问题(我省略了初始化部分)

$p = [System.Collections.Generic.Dictionary[String,String]]::new()
$p.Add('ITProduct','P1')

$telemetryClient.TrackMetric('TotalAppRegs',100, $p)
© www.soinside.com 2019 - 2024. All rights reserved.