通过 Powershell 在 Cosmos DB 中插入文档

Insert document on CosmosDB through Powershell

我正在使用 Invoke-RestMethod 发出 post 请求以在 CosmosDB 中创建一个新文档。到目前为止,我关注了这些链接:Invoking Rest API using PowerShell - CosmosDb , Add a Document to CosmosDB via the REST API using PowerShell and the official documentation.

我的脚本从外部服务中检索到这样的 object:

{
   "ObjectId": "bd33f6b5-a066-4f0f-8d1b-291a6a2b90ba",
   "Date":  "\/Date(1589379850000)\/",
   "Data": "{\"CreationTime\":\"2019-06-13T13:21:55\",\"Id\":\"e985f142-9359-4ebf-a319-7fa30b6c9987\", \"Fields\":[{\"Name\":\"foo\",\"Value\":\"bar\"}]}"
}

我的objective是要post领域Data进入宇宙。为此,我使用 $payload | Select-Object -expand Data 提取该字段。 (我有上面的 json 作为 PowerShell object)。由于这个提取的 object 是一个字符串,我将它传递给 Invoke-RestMethod:

Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body $payload

但我一直处于 Bad Request 状态。我还尝试了以下方法:

Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body ($payload | ConvertTo-Json -Depth 100)
Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $headers -Body ($payload | ConvertFrom-Json | ConvertTo-Json -Depth 100) 

注意:我能够使用 newtonsoftC# 中反序列化此字符串(我创建了一个函数来接收 PowerShell 请求)。我还能够通过 Postman 插入此文档。看起来问题出在请求的 body 中,因为使用 Postman 生成的 PowerShell 代码对我有用。

编辑:我在请求的 header 中传递内容类型 ("application/json")。当我直接将它传递给 Invoke-RestMethod

时它也会失败

谁能给个灯?对我来说应该没问题。

数据似乎被双重转换,要提取它你可以使用这个:

$json = '{"ObjectId": "bd33f6b5-a066-4f0f-8d1b-291a6a2b90ba", "Date":  "\/Date(1589379850000)\/", "Data": "{\"CreationTime\":\"2019-06-13T13:21:55\",\"Id\":\"e985f142-9359-4ebf-a319-7fa30b6c9987\", \"Fields\":[{\"Name\":\"foo\",\"Value\":\"bar\"}]}"}'
$data = $json | ConvertFrom-Json | Select-Object -ExpandProperty "Data" | ConvertFrom-Json
$body = $data | ConvertTo-Json -Depth 10

所以现在 $body 是一个合适的 JSON 对象,可以由 Invoke-RestMethod:

发送
Invoke-RestMethod -Method $verb -Uri $queryUri -Headers $headers -Body $payload -ContentType "application/json"

您的负载缺少必需的 id 属性:

请记住,REST API 用于核心 SQL API 操作。您的负载似乎是 Mongo 文档?

确保您也传递了分区键。参考:https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/PowerShellRestApi/PowerShellScripts/CreateItem.ps1