如何从 powershell 脚本在本地设置 cosmosdb 模拟器

How do I set up cosmosdb emulator locally from powershell script

我正在对我的 cosmos db 进行一些测试,我想使用 Cosmos Db 模拟器,通过脚本在本地进行设置。我想使用 PowerShell 脚本在 cosmos db 模拟器中使用 PowerShell 创建 Db、容器、填充测试数据,但我无法在线找到任何文档。有人可以指导我或帮助我这样做吗?到目前为止,我已经遵循 this 文档,它允许我使用 PowerShell

启动 CosmosDb 模拟器

I would like to use PowerShell scripts to create Db , containers , populate test data using PowerShell in cosmos db emulator but I couldn't find any documentation online.

Microsoft 提供的PowerShell 模块(Az.Cosmos) 只针对云端的Cosmos DB 帐户。从 5.8.0 版开始,它不支持 Cosmos DB 模拟器。

幸运的是,您可以使用社区解决方案:https://github.com/PlagueHO/CosmosDB

要为模拟器帐户创建上下文,您必须执行以下操作:

$cosmosDbContext = New-CosmosDbContext -Emulator -Database 'MyDatabase'

获得上下文后,您应该能够创建数据库和容器。例如:

New-CosmosDbDatabase -Context $cosmosDbContext -Id 'MyDatabase' -OfferThroughput 1200

New-CosmosDbCollection -Context $cosmosDbContext -Id 'MyNewCollection' -PartitionKey 'id' -OfferThroughput 50000

此项目上次更新是在 6 个月前,所以我不确定它是否具有您正在寻找的所有功能。

其他想法是利用 Cosmos DB .Net SDK 并在您自己的 PowerShell 脚本中使用它。

更新

这是我所做的:

  1. 我在 Admin 模式下打开了 PowerShell 控制台。
  2. 我使用 Install-Module -Name CosmosDB 安装了 Cosmos 模块。我最初收到一个错误(有关未找到模块的问题),我通过使用 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12.
  3. 将 TLS 命令设置为 1.2 来修复该错误
  4. 然后我使用你的命令启动了模拟器。
  5. 之后,我使用 $cosmosDbContext = New-CosmosDbContext -Emulator 创建了上下文。
  6. 在那之后,我在我的 Cosmos 模拟器帐户中列出了数据库并且能够成功地这样做。