Azure Automation PowerShell 5.1 Runbook无法解析JSON负载求助
PowerShell 5.1 Azure Automation Runbook 获取Webhook JSON负载的修正方案
错误原因
- 在PowerShell 5.1的Azure Automation Runbook中,
$WebhookData是预定义的PowerShell对象,而非JSON字符串。你直接对它执行ConvertFrom-Json,会导致PowerShell尝试将对象的字符串表示(非合法JSON)解析,从而抛出"Invalid JSON primitive: ."的错误。 - 你的代码混淆了PowerShell 7.2和5.1中
$WebhookData的处理逻辑——PS7.2的部分场景需要额外转换,但PS5.1中$WebhookData可直接访问属性。
修正后的代码
param ( [Parameter (Mandatory = $false)] [object] $WebhookData ) if ($WebhookData) { # 输出请求头(可选调试用) Write-Output $WebhookData.RequestHeader # 直接读取RequestBody(PS5.1中该属性为JSON字符串) if ($WebhookData.RequestBody) { try { $aliases = ConvertFrom-Json $WebhookData.RequestBody foreach ($x in $aliases) { $alias = $x.Alias $user = $x.User Write-Output "Alias: $alias" Write-Output "User: $user" } } catch { Write-Output "JSON解析失败: $_" } } else { Write-Output "无请求体数据" } } else { Write-Output "缺少Webhook数据" exit }
关键修正点
- 移除了错误的
$Payload = $WebhookData | ConvertFrom-Json步骤,直接通过$WebhookData.RequestBody获取请求体JSON字符串 - 添加
try/catch块捕获解析异常,便于排查潜在格式问题 - 优化了错误提示的清晰度
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

