Search code examples
powershellazure-automation

Passing multi-line KQL query to Az PowerShell cmdlet - error parsing query


Trying to pass a KQL string as parameter to cmdlet inside an Azure Automation Powershell 5.1 Runbook. But seems here-doc is giving error.

Please note need to avoid error-prone way of escaping each characters as it is cumbersome each time to modify back & forth the query.

Full query can be found here:


$query1 = @"
... multi-line KQL query...
"@

$output = Search-AzGraph -Query $query1 

This throws error:

Search-AzGraph : {
  "error": {
    "code": "BadRequest",
    "message": "Please provide below info when asking for support: timestamp = 2023-03-13T14:58:53.0156938Z, correlationId =
XXXX.XXX",
    "details": [
      {
        "code": "InvalidQuery",
        "message": "Query is invalid. Please refer to the documentation for the Azure Resource Graph service and fix the error before retrying."
      },
      {
        "code": "ParserFailure",
        "message": "ParserFailure",
        "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

Solution

    • Your query string contains tokens such as $right and $left ($right.controlId == $left.complianceControlId)

    • You're using the @"<newline>...<newline>@" to enclose your query string, i.e, the expandable (interpolating), double-quoted form of a PowerShell here-string.

      • Therefore, it is PowerShell that expands tokens such as $right in your query string, before you pass it on. (It replaces $right with the value of that PowerShell variable; if none is defined, $right expands to the empty string.)
    • If that is undesired, use @'<newline>...<newline>'@, i.e. the verbatim, single-quoted here-string form.

      • If you need to combine PowerShell's string expansion with pass-through $ characters, use @"<newline>...<newline>@" and escape the pass-through $ as `$

    Assuming that you want a verbatim query string:

    $query1 = @'
    ... multi-line KQL query...
    '@
    
    $output = Search-AzGraph -Query $query1