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

使用PowerShell调用Azure管理REST API创建带规则的NSG时遇类型转换错误

解决Azure REST API创建NSG时添加安全规则的InvalidRequestFormat错误

问题根源

你遇到的错误是因为PowerShell哈希表转JSON时的格式不符合Azure Management API对SecurityRule类型的要求——默认的JSON转换深度不足,导致嵌套的规则结构被截断,API无法识别为合法的安全规则对象。

具体解决步骤

  1. 严格匹配API要求构造规则结构
    确保每个安全规则的属性完全遵循Azure API定义,必填字段不能缺失,示例哈希表结构如下:

    $nsgBody = @{
        location = "eastus"
        properties = @{
            securityRules = @(
                @{
                    name = "Allow-HTTP-In"
                    properties = @{
                        protocol = "Tcp"
                        sourcePortRange = "*"
                        destinationPortRange = "80"
                        sourceAddressPrefix = "*"
                        destinationAddressPrefix = "*"
                        access = "Allow"
                        priority = 100
                        direction = "Inbound"
                        description = "Allow incoming HTTP traffic"
                    }
                }
            )
        }
    }
    
  2. 指定足够深度转换为JSON
    PowerShell的ConvertTo-Json默认深度为2,无法完整转换嵌套的安全规则结构,必须手动指定足够大的深度值:

    $jsonBody = $nsgBody | ConvertTo-Json -Depth 10
    

    转换后可以输出$jsonBody验证,确保安全规则是完整的嵌套JSON对象,而非哈希表的字符串表示。

  3. 发送请求时指定正确的Content-Type
    调用REST API时必须明确告知接口接收的是JSON格式数据:

    $response = Invoke-RestMethod -Uri $nsgApiUri -Method Put -Headers $headers -Body $jsonBody -ContentType "application/json"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:25:23