PowerShell调用AppInsight REST API时遇Unexpected Token错误求助
解决PowerShell中传递KQL查询到Azure Application Insights API的转义错误
错误原因
问题出在PowerShell双引号字符串的解析逻辑上:当你在双引号包裹的KQL查询里写\"时,PowerShell会将其解析为字面双引号,导致KQL字符串提前闭合,触发语法解析错误。
优雅解决方案
方案1:用KQL原生函数pack生成JSON(推荐)
直接使用KQL的pack函数替代手动拼接JSON字符串,既避免转义问题,又更符合KQL的最佳实践:
$appKey="myApiKey" $appId="myApiAppId" $resource="https://api.applicationinsights.io" $secpasswd = ConvertTo-SecureString $appKey -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ($appId, $secpasswd) Connect-AzAccount -ServicePrincipal -Tenant "myTenantId" -Credential $mycreds $res=Get-AzAccessToken -ResourceUrl $resource $headers=@{"Authorization"="Bearer "+$res.Token} # 使用pack函数生成JSON格式的TimeProperties $body=@{ "query" = "app('22222222-2222-2222-2222-222222222222').customEvents | where name == 'ItemProcessed' | where timestamp < now(-0d) and timestamp > now(-5d) | project timestamp, customDimensions, customMeasurements | extend TimeProperties = pack('DateTimeStamp', timestamp) | project TimeProperties,customDimensions,customMeasurements" } | ConvertTo-Json $c = Invoke-RestMethod 'https://api.applicationinsights.io/v1/workspaces/11111111-1111-1111-1111-111111111111/query' -Method 'POST' -Headers $headers -Body $body -ContentType "application/json" $c.tables | ConvertTo-Json
方案2:用单引号包裹KQL查询
将KQL查询用PowerShell单引号包裹,这样内部的双引号不需要转义,PowerShell会原样保留字符串内容:
$body=@{ "query" = 'app(''22222222-2222-2222-2222-222222222222'').customEvents | where name == ''ItemProcessed'' | where timestamp < now(-0d) and timestamp > now(-5d) | project timestamp, customDimensions, customMeasurements | extend TimeProperties = strcat(''{"DateTimeStamp":"'',timestamp,''"}''), customDimensions,customMeasurements | project TimeProperties,customDimensions,customMeasurements' } | ConvertTo-Json
注意:单引号内的单引号需要用两个单引号''转义
方案3:用PowerShell Here-String定义查询
对于多行复杂查询,Here-String是可读性最好的选择,内部双引号无需转义:
$kqlQuery = @" app('22222222-2222-2222-2222-222222222222').customEvents | where name == 'ItemProcessed' | where timestamp < now(-0d) and timestamp > now(-5d) | project timestamp, customDimensions, customMeasurements | extend TimeProperties = strcat('{"DateTimeStamp":"',timestamp,'"}'), customDimensions,customMeasurements | project TimeProperties,customDimensions,customMeasurements "@ $body=@{ "query" = $kqlQuery } | ConvertTo-Json
内容的提问来源于stack exchange,提问作者AQuader
相关产品推荐
相关产品推荐

