如何从 Powershell 脚本非交互地运行 Azure Log Analytics 查询?

mar*_*ark 1 powershell azure azure-application-insights

鉴于:

  • 我有一个 Azure 帐户(MSDN 权益)。
  • 我有一个控制台应用程序将自定义 AppInsights 指标发送到我的 AppInsights 工作区。

我想从 PowerShell 脚本中查询这些指标。

我确实尝试通过谷歌搜索找到解决方案 - 没有成功。并不是说没有关于该主题的帖子 - 我只是无法按照这些帖子进行操作。

问题的要点是如何在没有用户交互的情况下做到这一点。

小智 7

$WorkspaceName = 'weu-co-law-security-01'
$ResourceGroupName = 'aaa-co-rsg-security-01'
$Workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName $ResourceGroupName -Name $WorkspaceName
$QueryResults = Invoke-AzOperationalInsightsQuery -Workspace $Workspace -Query 'AuditLogs | where OperationName == "Add member to group" | project TargetResources[0].displayName'
$QueryResults.Results
Run Code Online (Sandbox Code Playgroud)


Tat*_*ela 6

您可以使用az cli的application-insights扩展来执行此操作。

az extension add -n application-insights
az monitor app-insights query --apps "$my-app-name" --resource-group "$my-resource-group" --offset 24H --analytics-query 'requests | summarize count() by bin(timestamp, 1h)'
Run Code Online (Sandbox Code Playgroud)

这是一个 powershell 脚本,它可以从给定的应用程序洞察实例和资源组中的文件运行 kusto 查询,并将数据作为 powershell 表返回:

<#
.SYNOPSIS

Run query in application insights and return Powershell table

.PARAMETER filename

File name of kusto query

.PARAMETER app 

Application Insights instance name

.PARAMETER rg

Resource group name

.EXAMPLE

Search-AppInsights -filename file.kusto -app my-app-name -rg my-resource-group-name

#>
param([string] $filename, [string]$app, [string]$rg)

$query = Get-Content $filename
$data = az monitor app-insights query --apps "$app" --resource-group "$rg" --offset 48H --analytics-query "$query" | ConvertFrom-Json
$cols = $data.tables.columns | % {  $_.name }
$data.tables.rows | % {
    $obj = New-Object -TypeName psobject
    for ($i=0; $i -lt $cols.Length; $i++) {
    $obj | Add-Member -MemberType NoteProperty -Name $cols[$i] -Value $_[$i]
    }
    $obj
}
Run Code Online (Sandbox Code Playgroud)