gpt4 book ai didi

azure - 如何使用 PowerShell 脚本将数据从外部文件插入 Azure Cosmos DB?

转载 作者:行者123 更新时间:2023-12-03 00:43:21 25 4
gpt4 key购买 nike

我有一个 PowerShell 脚本,用于在 Azure Cosmos DB 中创建数据库和集合,并且我可以使用以下 PowerShell 脚本在集合中插入一些虚拟记录。

    #region Parameters

$clientId= "< Replace with your clientId >"
$clientSecret= "< Replae with you clientsecret >"
$subscriptionName= "< Replace with your subscription name>"
$tenantId= "< Replace with your tenant Id>"
$resourceGroupName= "Demo"
$connectionString='< Replace wtih Cosmos DB Connection String >'
$cosmosDBAccounts= @('demo-account-01')
#$accountName='demo-account-01'
$databaseName='demo-db-01'
$collectionName='demo-collection-01'
$partitionkey= 'demo'

#endregion

#region Login into Azure using Interactive Mode or Service Principal details

# sign in
Write-Host "Logging in...";

#Connect-AzAccount
$securePassword = $clientSecret | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $clientId, $securePassword
Connect-AzAccount -Credential $cred -ServicePrincipal -TenantId $tenantId

#Set the current azure subscription
Select-AzSubscription -subscription $subscriptionName

#endregion

#region Create Collection and insert some data into it

foreach($cosmosDBAccount in $cosmosDBAccounts){

$cosmosDbContext = New-CosmosDbContext -Account $cosmosDbAccount -Database $databaseName -ResourceGroup $resourceGroupName
New-CosmosDbDatabase -Context $cosmosDbContext -Id $databaseName
New-CosmosDbCollection -Context $cosmosDbContext -Id $collectionName -PartitionKey $partitionkey -OfferThroughput 2500 -Database $databaseName

0..9 | Foreach-Object {

$document = @"
{
"id": "$([Guid]::NewGuid().ToString())",
"name": "pradeep",
"demo": "XYZ"
}
"@

New-CosmosDbDocument -Context $cosmosDbContext -CollectionId $collectionName -DocumentBody $document -PartitionKey "XYZ"

}
}

#endregion

但我想将记录从外部文件插入 Azure Cosmos DB,而不是将 JSON 数据直接放入 PowerShell 脚本中。

那么,谁能建议我如何将数据从外部文件插入到 Azure Cosmos DB 中。

最佳答案

将代码片段添加到您需要的位置,它将在集合中创建 .json 文件的文档。

$json = Get-Content 'C:\Users\joyw\Desktop\cosmos.json' | Out-String | ConvertFrom-Json
$cosmosDbContext = New-CosmosDbContext -Account $cosmosDbAccount -Database $databaseName -ResourceGroup $resourceGroupName

foreach($item in $json){
$document = $item | ConvertTo-Json | Out-String
New-CosmosDbDocument -Context $cosmosDbContext -CollectionId $collectionName -DocumentBody $document -PartitionKey "XYZ"

}

我的.json文件:

[{
"id": "1",
"name": "pradeep",
"demo": "XYZ"
}, {
"id": "2",
"name": "pradeep12",
"demo": "XYZ"
}, {
"id": "3",
"name": "pradeep123",
"demo": "XYZ"
}, {
"id": "4",
"name": "pradeep1234",
"demo": "XYZ"
}]

结果:

enter image description here

登录门户:

enter image description here

关于azure - 如何使用 PowerShell 脚本将数据从外部文件插入 Azure Cosmos DB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com