You need to enable JavaScript to run this app. PowerShell调用Palo Alto XDR API时Invoke-RestMethod报request_data类型错误
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Palo Alto XDR API时Invoke-RestMethod报request_data类型错误

报错根因

request_data必须为dict类型的提示,本质是你传递的请求体结构不满足API的类型校验要求,具体是三个可直接定位的问题:

  • 你把request_data赋值为带引号的字符串'{}'。在PowerShell中这是纯文本内容,经过ConvertTo-Json序列化后,最终发给API的是被引号包裹的字符串值"request_data": "{}",而不是API要求的空JSON对象(字典结构),自然会被判定为类型不匹配。
  • PowerShell 5.1及以上版本内置的ConvertTo-Json默认仅支持2层嵌套序列化,你代码里的请求体有三层嵌套(根请求体→filters过滤器→sort排序规则),不指定序列化深度的话,深层的sort字段会被截断成无效字符串,同样会触发输入校验失败。
  • 遍历逻辑存在层级取错的隐患:该XDR全量端点接口的返回结构中,真实的端点列表存放在reply.endpoints字段下,reply根节点还包含总条数、查询游标等元属性,直接遍历$endpoints.reply会遍历到这些元属性,根本拿不到有效的端点ID。
修复后的可用代码
$ContentType = "application/json"
$AuthHeaders = @{
    "x-xdr-auth-id" = "1"
    "Authorization" = "<API-KEY_Goes_Here>"
}
$URL_All = 'https://api-<company>.xdr.eu.paloaltonetworks.com/public_api/v1/endpoints/get_endpoints/'
$URLEndpoint = 'https://api-<company>.xdr.eu.paloaltonetworks.com/public_api/v1/endpoints/get_endpoint/'

# 调用全量端点查询接口
$endpointsAll = Invoke-RestMethod -uri $URL_All -method POST -Headers $AuthHeaders -ContentType $ContentType -Verbose

# 修正列表获取层级,从reply节点下取真实端点列表
$endpointList = $endpointsAll.reply.endpoints
if ($endpointList.count -lt 1){
    write-host " API didn't return any endpoint - ending script "
    break
}
write-host "Found $($endpointList.count) endpoints"

# 预先初始化结果数组,避免第一次循环的+=运算报错
$Endpoint_full = @()
foreach ($endpoint in $endpointList) {
    if($endpoint.agent_id -ne $null){
        # 替换字符串形式的request_data为空哈希表,保证序列化后为真正的JSON字典
        $request = @{
            request_data = @{}
            filters      = @(
                @{
                    field       = "endpoint_id_list"
                    operator    = "in"
                    Value       = @($endpoint.agent_ID)
                }
            )
            Search_from = 0
            Search_to   = 1
            sort        = @{ 
                field   = "last_seen"
                keyword = "desc"
            }
        } | ConvertTo-Json -Depth 10 # 指定足够的序列化深度,避免深层嵌套被截断

        $singleEndpoint = Invoke-RestMethod -uri $URLEndpoint -method POST -Body $request -Headers $AuthHeaders -ContentType $ContentType -Verbose
        $Endpoint_full += $singleEndpoint
    }
}
额外校验规则提示
  • 该XDR API要求filters字段为数组格式,即使只有单条过滤规则,也要用方括号包裹为数组结构,单对象格式会触发输入校验失败。
  • 过滤器对应的Value字段为列表类型,单个ID也要用数组形式包裹,不要直接传纯字符串值。
  • 所有超过2层的嵌套请求结构,在使用ConvertTo-Json序列化时必须加-Depth参数,指定足够的深度(一般设为10即可覆盖绝大多数API的请求结构),避免序列化丢值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 08:36:04