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

向Az PowerShell cmdlet传递多行KQL查询时解析出错

在Azure Automation PowerShell 5.1 Runbook中解决多行KQL查询的解析错误

问题场景

在Azure Automation的PowerShell 5.1 Runbook中,使用here-doc语法定义多行KQL查询字符串,并传入Search-AzGraph cmdlet时触发解析错误。需要找到无需逐个转义字符的解决方案,避免修改查询时的繁琐操作。

使用的代码示例

$query1 = @"
... 多行KQL查询内容...
"@

$output = Search-AzGraph -Query $query1 

抛出的错误信息

Search-AzGraph : {
  "error": {
    "code": "BadRequest",
    "message": "请求支持时请提供以下信息:时间戳 = 2023-03-13T14:58:53.0156938Z,关联ID =XXXX.XXX",
    "details": [
      {
        "code": "InvalidQuery",
        "message": "查询无效。请参考Azure资源图服务文档,修复错误后重试。"
      },
      {
        "code": "ParserFailure",
        "message": "解析器失败",
        "line": 1,
        "characterPositionInLine": 3815,
        "token": "."
      }
    ]
  }
}
At line:1 char:11
+ $output = Search-AzGraph -Query $the_query
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Search-AzGraph], ErrorResponseException
    + FullyQualifiedErrorId : BadRequest,Microsoft.Azure.Commands.ResourceGraph.Cmdlets.SearchAzureRmGraph

解决方案

1. 清理here-doc中的隐藏字符

PowerShell 5.1的here-doc可能引入多余换行、制表符或不可见字符,导致KQL解析失败。通过正则替换合并为单行并清理空白:

$query1 = @"
... 多行KQL查询内容...
"@ -replace '\r?\n', ' ' | Trim()

2. 直接使用字符串字面量拼接

放弃here-doc,用连续字符串字面量拼接,既保持可读性又避免隐藏字符问题:

$query1 = 
"SecurityResources
| where type == 'microsoft.security/assessments'
| extend complianceState = properties.complianceState,
         assessmentName = properties.displayName,
         resourceId = tolower(properties.resourceDetails.id)
| ... 其他查询部分 ..."

3. 定位并修复KQL语法错误

根据错误提示,检查第1行3815位置的.字符:

  • 排查是否存在多余点号(如properties..name)
  • 验证属性访问、函数调用的语法正确性
  • 先在Azure资源图资源管理器中测试查询,确认无误后再复制到Runbook

4. 读取外部KQL文件(可选)

将复杂查询保存为单独的.kql文件,通过Get-Content读取:

$query1 = Get-Content -Path ".\compliance-query.kql" -Raw | Trim()
$output = Search-AzGraph -Query $query1

此方式便于单独维护查询,需确保Runbook可访问该文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:05:12