Last active
September 27, 2019 07:54
-
-
Save ulve/892359e506f3489b76e075743d6604a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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