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

PowerShell中Invoke-WebRequest的POST请求Body配置问题求助

PowerShell Invoke-WebRequest Body 参数错误修正

你的代码核心问题是混淆了PowerShell哈希表语法和JSON语法:

  • PowerShell哈希表(@{})的键值对必须用=分隔,而非:
  • 直接写key: value属于JSON语法,不能放在PowerShell哈希表的@{}结构里

正确写法步骤

  1. 用PowerShell哈希表语法构建参数对象
  2. 通过ConvertTo-Json将哈希表转为JSON字符串,作为Invoke-WebRequest的Body参数

修正后的代码:

# 正确构建PowerShell哈希表
$param = @{
    name     = "MDE.Windows"
    id       = "$resourceId/extensions/MDE.Windows"
    type     = "Microsoft.Compute/virtualMachines/extensions"
    location = "westeurope"
    properties = @{
        autoUpgradeMinorVersion = $true
        publisher               = "Microsoft.Azure.AzureDefenderForServers"
        type                    = "MDE.Windows"
        typeHandlerVersion      = "1.0"
        settings = @{
            azureResourceId               = $resourceId
            defenderForServersWorkspaceId = $subscriptionId
            vNextEnabled                  = "true"
            forceReOnboarding             = $true
            provisionedBy                 = "Manual"
        }
        protectedSettings = @{
            defenderForEndpointOnboardingScript = $defenderForEndpointOnboardingScript
        }
    }
}

# 转换为JSON并作为Body传入Invoke-WebRequest
$jsonBody = $param | ConvertTo-Json -Depth 10
Invoke-WebRequest -Uri "你的请求URL" -Method Post -Body $jsonBody -ContentType "application/json"

关键说明

  • 哈希表嵌套时,内部对象也要用@{}声明(比如properties、settings里的内容)
  • ConvertTo-Json默认深度为2,这里嵌套层级较多,必须指定-Depth 10避免JSON结构截断
  • PowerShell中布尔值需用$true/$false,不能直接写true/false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:05:23