Technical Article

Powershell Script - Azure cosmos DB(SQL API)

,

Hello Everyone

I have created a Powershell script for Azure comos db. This scripts is capable of inserting,fetching and deleting a document from Azure cosmos DB. Pls test them in your environment and provide me your feedback.

I used Rest API for this script creation and tested it on SQL API. It might work with other API's as well. Need to test that as well 😛

Thanks,

Dinesh kumar

# add necessary assembly
#
Add-Type -AssemblyName System.Web

# generate authorization key
Function Generate-MasterKeyAuthorizationSignature
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$verb,
[Parameter(Mandatory=$true)][String]$resourceLink,
[Parameter(Mandatory=$true)][String]$resourceType,
[Parameter(Mandatory=$true)][String]$dateTime,
[Parameter(Mandatory=$true)][String]$key,
[Parameter(Mandatory=$true)][String]$keyType,
[Parameter(Mandatory=$true)][String]$tokenVersion
)

$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)

$payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
$signature = [System.Convert]::ToBase64String($hashPayLoad);

[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}

# Function to insert document in Azure Cosmos DB
Function Post-CosmosDb
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$DataBaseId,
[Parameter(Mandatory=$true)][String]$CollectionId,
[Parameter(Mandatory=$true)][String]$MasterKey,
[Parameter(Mandatory=$true)][String]$JSON
)

$Verb = "POST"
$ResourceType = "docs";
$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"
$partitionkey = "[""$(($JSON |ConvertFrom-Json)."Partition Key Name""")""]"

$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-documentdb-partitionkey"=$partitionkey;"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink/docs"

#[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $JSON
#return $result.statuscode

}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey
$CosmosDBEndPoint = "https://XXXXXXX.documents.azure.com:443/"
$DatabaseId = "Database NameID"
$CollectionId = "Collection Name  ID"
$MasterKey = "Read write key value"

$document = @"    # Values to be inserted in JSON format
{
`"id`": `"$([Guid]::NewGuid().ToString())`",  
`"Name`": `"Dinesh Kumar`",
`"Department`": `"IT`"
}
"@

# execute
Post-CosmosDb -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -MasterKey $MasterKey -JSON $document -Verbose -Debug

# Function to fetch the data from single document in JSON Format 
Function Get-CosmosDocument 
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$DataBaseId,
[Parameter(Mandatory=$true)][String]$CollectionId,
[Parameter(Mandatory=$true)][String]$MasterKey

)
$Verb = "GET"
$ResourceType = "docs";
$DocumentID = "Document id"
$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId/docs/$DocumentID"

$KeyValue = "Key Value"
$partitionkey = "[""$($KeyValue)""]"
#$partitionkey

$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-documentdb-partitionkey"=$partitionkey;"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink"

Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $header



}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey
$CosmosDBEndPoint = "https://XXXXXX.documents.azure.com:443/"
$DatabaseId = "Database NameID"
$CollectionId = "Collection name  ID"
$MasterKey = "Read Only key value"

# execute
Get-CosmosDocument -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -MasterKey $MasterKey -Verbose 



# Function to delete document from Cosmos DB
Function Delete-CosmosDbDocument
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$DataBaseId,
[Parameter(Mandatory=$true)][String]$CollectionId,
[Parameter(Mandatory=$true)][String]$MasterKey
#[Parameter(Mandatory=$true)][String]$JSON
)

$Verb = "DELETE"
$ResourceType = "docs";
$DocumentID = "Document id whcih needs to be deleted"
$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId/docs/$DocumentID"
$KeyValue = "Partition Key value"
$partitionkey = "[""$($KeyValue)""]"



$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = @{authorization=$authHeader;"x-ms-version"="2015-12-16";"x-ms-documentdb-partitionkey"=$partitionkey;"x-ms-date"=$dateTime}
#$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink"

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Invoke-RestMethod -Method $Verb -Uri $queryUri -Headers $header -Verbose 
#return $result.statuscode


}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey
$CosmosDBEndPoint = "https://XXXXXXXX.documents.azure.com:443/" #URI
$DatabaseId = "Database Nameid"
$CollectionId = "Collection Name  ID"
$MasterKey = "Read Write Key value"


# execute
Delete-CosmosDbDocument -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -MasterKey $MasterKey  -Verbose

Rate

★ ★ ★ ★ ★ ★ ★ ★ ★ ★

You rated this post out of 5. Change rating

Share

Share

Rate

★ ★ ★ ★ ★ ★ ★ ★ ★ ★

You rated this post out of 5. Change rating