You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在直接查询Azure Data Explorer集群的PowerShell等效方法?

如何在Az.Kusto 2.1.0版本下用PowerShell查询Azure Data Explorer集群

背景说明

PowerShell函数Invoke-AzOperationalInsightsQuery支持向App Insights资源传递任意KQL字符串,示例代码如下:

Set-AzContext -Subscription "my-sub"
$workspaceName = "vl-loganalytics-workspace"
$workspaceRG = "vl-loganalytics"

$WorkspaceID = (Get-AzOperationalInsightsWorkspace -Name $workspaceName -ResourceGroupName $workspaceRG).CustomerID

$query = "print current_cluster_endpoint()"

$kqlQuery = Invoke-AzOperationalInsightsQuery -WorkspaceId $WorkspaceID -Query $query
$kqlQuery.Results

截至Az.Kusto模块2.1.0版本,官方未提供直接查询Azure Data Explorer(ADX)集群的公开PowerShell函数,以下是几种社区常用的临时解决方案:

方案1:直接调用ADX REST API

通过Invoke-RestMethod调用ADX的查询REST API,需先获取Azure AD令牌完成身份验证:

# 获取ADX集群对应的Azure AD访问令牌
$tenantId = "你的租户ID"
$clusterUri = "https://你的集群名称.kusto.windows.net"
$resource = "https://kusto.azure.com/"
$token = (Get-AzAccessToken -ResourceUrl $resource -TenantId $tenantId).Token

# 构造查询请求参数
$databaseName = "目标数据库名称"
$query = "StormEvents | take 10"
$headers = @{
    "Authorization" = "Bearer $token"
    "Content-Type"  = "application/json"
}
$body = @{
    db   = $databaseName
    csl  = $query
} | ConvertTo-Json

# 发送查询并获取结果
$response = Invoke-RestMethod -Uri "$clusterUri/v1/rest/query" -Method Post -Headers $headers -Body $body
$response.Tables.Rows

方案2:借助Kusto .NET SDK实现

通过PowerShell加载Kusto .NET客户端程序集,直接调用SDK的查询能力:

# 首次运行需安装Kusto客户端NuGet包
Install-Package Microsoft.Azure.Kusto.Data -Scope CurrentUser

# 加载相关程序集(路径需替换为实际NuGet包安装路径)
Add-Type -Path "C:\Users\你的用户名\.nuget\packages\microsoft.azure.kusto.data\最新版本号\lib\netstandard2.0\Microsoft.Azure.Kusto.Data.dll"
Add-Type -Path "C:\Users\你的用户名\.nuget\packages\microsoft.azure.kusto.data\最新版本号\lib\netstandard2.0\Microsoft.Azure.Kusto.Data.Net.Client.dll"

# 创建ADX查询客户端
$clusterUri = "https://你的集群名称.kusto.windows.net"
$databaseName = "目标数据库名称"
$kcsb = New-Object Microsoft.Azure.Kusto.Data.KustoConnectionStringBuilder($clusterUri, $databaseName)
$kcsb = $kcsb.WithAadAzCliAuthentication() # 使用Az CLI已登录的身份验证
$queryClient = [Microsoft.Azure.Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider($kcsb)

# 执行查询并读取结果
$query = "StormEvents | take 10"
$reader = $queryClient.ExecuteQuery($query)
while ($reader.Read()) {
    $resultRow = @{}
    for ($i=0; $i -lt $reader.FieldCount; $i++) {
        $resultRow[$reader.GetName($i)] = $reader.GetValue($i)
    }
    $resultRow
}

方案3:使用社区维护的PowerShell模块

社区提供的Az.Kusto.Community模块(非官方)封装了ADX查询的简化命令,可通过PowerShell Gallery安装使用:

# 安装社区模块
Install-Module -Name Az.Kusto.Community -Scope CurrentUser -Force

# 执行ADX查询
Invoke-KustoQuery -ClusterUri "https://你的集群名称.kusto.windows.net" -Database "目标数据库名称" -Query "StormEvents | take 10"

内容的提问来源于stack exchange,提问作者Peter Vandivier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:45:29