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

使用PowerShell无法在Azure Cosmos DB(NoSQL API)中创建记录

Cosmos DB NoSQL API 插入记录失败的问题排查与修复

你的代码存在几个关键问题,导致插入操作失败,以下是具体问题和修复方案:

1. JSON文档格式错误(id字段缺少引号)

构造JSON时,id字段的值直接使用变量$id但未添加引号,生成的JSON语法无效。正确写法需给$id加上双引号:

$document = @"
{
    "id": "$id",
    "productName": "widget-211",
    "key": "211"
}
"@

2. PartitionKey参数传值错误

New-CosmosDbDocument的-PartitionKey参数需要传入分区键的具体值,而非分区键路径。如果容器分区键是/id,应传入生成的$id变量,而非字符串"/id":

New-CosmosDbDocument -Context $cosmosDbContext -CollectionId $CollectionId -DocumentBody $document -PartitionKey $id

3. 函数名拼写错误(非致命但需修正)

函数名InsterCosmosDbRecord拼写错误,正确应为InsertCosmosDbRecord,虽不影响执行,但建议修正以保证代码可读性。

4. 模块安装权限问题(潜在风险)

执行Install-Module时若无管理员权限可能失败,可添加-Scope CurrentUser参数规避权限要求:

Install-Module -Name CosmosDB -RequiredVersion 4.7.0 -AllowClobber -Force -Scope CurrentUser

修复后的完整代码示例

#region param
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[string]$resourceGroup = "rg_name",

[Parameter(Mandatory = $false)]
[string]$cosmosAccount = "test",

[Parameter(Mandatory = $false)]
[string]$database = "Testing",

[Parameter(Mandatory = $false)]
[string]$CollectionId = "testcontainer"
)
#endregion param

Function InsertCosmosDbRecord
{
 $clientId       = "{client_id}"
 $clientSecret   = "{client_secret}"
 $tenantId       = "{tenant_id}"
 $securePassword = ConvertTo-SecureString -String $clientSecret -AsPlainText -Force

  $credential     = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $clientId, $securePassword
  Connect-AzAccount -ServicePrincipal -Credential $credential -Tenant $tenantId

    $module = Get-InstalledModule -Name 'CosmosDB' -ErrorAction SilentlyContinue

    if($module -ne $null)
    {
    write-host "module CosmosDB available"
     }
    else
    {
    write-host "module CosmosDB not available download in progress"
    Install-Module -Name CosmosDB -RequiredVersion 4.7.0 -AllowClobber -Force -Scope CurrentUser
    }
    
    $id = $([Guid]::NewGuid().ToString())
    
    $document = @"
    {
        "id": "$id",
        "productName": "widget-211",
        "key": "211"
    }
  "@
  $cosmosDbContext = New-CosmosDbContext -Account $cosmosAccount -Database $database -ResourceGroup $resourceGroup
  
  write-host "Document: "  $document
  New-CosmosDbDocument -Context $cosmosDbContext -CollectionId $CollectionId -DocumentBody $document -PartitionKey $id
   
  }

  InsertCosmosDbRecord

额外建议:执行Get-InstalledModule时加上-ErrorAction SilentlyContinue,避免模块未安装时抛出无意义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:32:48