Save data To Azure CosmosDb using power shell scripts

In this article, we are going to demonstrate how we can use PowerShell scripts and insert bulk data from a file into cosmosDb leveraging CosmosDb PowerShell package

Pushing Data To CosmosDb From Azure Pipeline Using PowerShell

CosmosDb is a fully managed, nosql, non relational database which allows us to store data durably with several ACID configurations. Microsoft guarantees speed at any scale

Let's get started and write the code.

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

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

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

	[Parameter(Mandatory = $false)]
	[string]$filePath = "../file.json"
)
#endregion param

Function UpdateCosmosDb
{	
	$User = "Azure-userId"
	$PWord = ConvertTo-SecureString -String "Password" -AsPlainText -Force
	$tenant = "Azure Tenant Id"
	$subscription = "cAzure Subscription Id"
	$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord	
	Connect-AzAccount -Credential $Credential -Tenant $tenant -Subscription $subscription #Login into your azure account

	$module = Get-InstalledModule -Name 'CosmosDB'
	if($module -ne $null)
	{
		write-host "module CosmosDB avaiable"
	}
	else
	{
		write-host "module CosmosDB not avaiable download in progress"
		Install-Module -Name CosmosDB -AllowClobber -force
	}
	$items = Get-Content -path $filePath -Encoding UTF8 -Raw | ConvertFrom-Json		
	$cosmosDbContext = New-CosmosDbContext -Account $cosmosAccount -Database $database -ResourceGroup $resourceGroup		
	foreach($item in $items)
	{
		$id = $item.id		
		$item | Add-Member -NotePropertyName id -NotePropertyValue $id #creates new property in josn		
		$document = $item | ConvertTo-Json #converts the object into json		
		$query = "SELECT c.id FROM c WHERE c.id = '$id'"	
		write-host $query
		$existingDocument = Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId 'ContainerId' -Query $query		
		if($existingDocument -ne $null)
		{
			write-host "Remove $document"
			Remove-CosmosDbDocument -Context $cosmosDbContext -CollectionId 'ContainerId' -PartitionKey "$id" -Id "$id"
		}
		write-host "New $document"
		New-CosmosDbDocument -Context $cosmosDbContext -CollectionId 'ContainerId' -DocumentBody $document -PartitionKey "$id"
	}	
}
UpdateCosmosDb

Note
If you are executing the above PowerShell in Azure pipeline with let's say contributor role then you don't need to perform Line No. 20 to 26

Keep coding

Cheers


Similar Articles