powershell - 将值添加到数组并将其作为 json 有效负载发送 - Powershell Azure

标签 powershell azure-cli

我正在使用 powershell(特别是 Azure CLI)从服务获取数据、向列表添加值并向 URL 发送补丁/帖子。

这是获取数据列表的 URL:

$uriList = az rest --method get --uri "https://graph.microsoft.com/beta/applications/$objectId" --header "$header" --query spa.redirectUris | ConvertFrom-Json

这将返回一个字符串数组。

['a', 'b', 'c', 'd', 'e']

if ($uriList -notcontains "f") {
    $uriList  += "f"
}

$uriListJSON = $uriList | ConvertTo-Json

在上面,我已将“f”添加到数组中,我想将其发送到网址,如下所示:

$body = "{spa:{redirectUris: $uriListJSON}}"

az rest --method patch --uri "https://graph.microsoft.com/beta/applications/$objectId"--headers "$header"--body "$body"

我收到错误:

Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format."

请告诉我我做错了什么。我将 uriListJSON 输出到一个文件,并针对 json 验证器运行它,结果通过了。

当我将所有内容硬编码到像这样的网址时

az rest --method patch --uri "https://graph.microsoft.com/beta/applications/$objectId" --headers $header --body "{spa: {redirectUris: ['a', 'b', 'c', 'd', 'e', 'f']}}"

它就像一个魅力。

最佳答案

您的 JSON 转换结果会生成一个字符串,该字符串符合标准 - 嵌入双引号 ("):

PS> ("['a', 'b', 'c', 'd', 'e']" | ConvertFrom-Json) + 'f' | ConvertTo-Json -Compress

["a","b","c","d","e","f"]

由于您要将结果字符串传递给外部程序 - az - 从 PowerShell 7.2 开始,悲惨的现实是需要额外的手动\ - 转义嵌入的 " 字符参数中的strong>。
这个可能会在未来版本中得到修复,可能需要选择加入。请参阅this answer了解详情。

因此:

$uriListJSON = ("['a', 'b', 'c', 'd', 'e']" | ConvertFrom-Json) + 'f' | ConvertTo-Json -Compress

$body = "{ \`"spa\`": { \`"redirectUris\`": $($uriListJSON -replace '"', '\"') } }"

请注意,虽然 az 可能不需要,但上面使用了严格符合标准的 JSON 字符串,其中 JSON 的 逐字 部分的属性名称字符串也被 "..." 引用,这需要两者转义对于 PowerShell (`") < em>和手动\-转义外部程序;组合起来:\`"

关于powershell - 将值添加到数组并将其作为 json 有效负载发送 - Powershell Azure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70228953/

相关文章:

powershell - 有没有办法在 Windows 终端中激活 Poetry 的彩色输出?

Powershell 命令在 Windows 2016 上运行乱序

arrays - PowerShell:两个以上数组的交集

azure - 使用 Powershell/Azure CLI 禁用数据中心对 Cosmos DB 的网络访问

Azure APIM导入graphql api

powershell - 使用 Powershell 在 msi 中设置摘要信息

windows - 当记事本不是默认应用程序时,如何从 Windows 资源管理器运行 PowerShell 脚本?

azure - 哪里列出了 az 角色分配

Azure staticwebapp 不允许在终端中使用 Azure CLI 添加值为 "&"的配置