Skip to content

Instantly share code, notes, and snippets.

@ulve
Last active September 27, 2019 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulve/892359e506f3489b76e075743d6604a1 to your computer and use it in GitHub Desktop.
Save ulve/892359e506f3489b76e075743d6604a1 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Query a CosmoDb.
.DESCRIPTION
This command will query a cosmos db and return the results as an object.
.PARAMETER EndPoint
The endpoint to the CosmosDb Account.
.PARAMETER DatabaseId
The database to issue the query to.
.PARAMETER CollectionId
The collection to query.
.PARAMETER Key
The key used to access the CosmosDb database account.
.PARAMETER Query
The query to run
.EXAMPLE
Invoke-CosmosDbQuery -EndPoint https://my-cosmos-db.documents.azure.com:443/ -DatabaseId MyDatabase -CollectionId authDocuments -Key asdf1234 -Query "SELECT * from c"
#>
function Invoke-CosmosDbQuery
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$DatabaseId,
[Parameter(Mandatory=$true)][String]$CollectionId,
[Parameter(Mandatory=$true)][String]$Key,
[Parameter(Mandatory=$true)][String]$Query
)
function GenerateSignature([String]$resourceLink, [String]$dateTime, [String]$key)
{
$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)
$payLoad = "post`ndocs`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=master&ver=1.0&sig=$signature")
}
$ResourceLink = "dbs/$DatabaseId/colls/$CollectionId"
$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = GenerateSignature -resourceLink $ResourceLink -key $Key -dateTime $dateTime
$queryJson = @{query=$Query} | ConvertTo-Json -Compress
$header = @{authorization=$authHeader;"x-ms-documentdb-isquery"="True";"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
$contentType= "application/query+json"
$queryUri = "$EndPoint$ResourceLink/docs"
Invoke-RestMethod -Method "POST" -ContentType $contentType -Uri $queryUri -Headers $header -Body $queryJson
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment