I want to connect to CosmosDB in Azure Portal to fetch data using a query. I need to do this using Azure Powershell (Runbook). Please suggest how to establish connection and execute some random query using Azure Powershell.
Thanks!!
I want to connect to CosmosDB in Azure Portal to fetch data using a query. I need to do this using Azure Powershell (Runbook). Please suggest how to establish connection and execute some random query using Azure Powershell.
Thanks!!
$cosmosDBAccountKey = Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName -Name $accountName
$key = $cosmosDBAccountKey.PrimaryMasterKey
$primaryKey = ConvertTo-SecureString -String $key -AsPlainText -Force
$cosmosDbContext = New-CosmosDbContext -Account $accountName -Database $databaseName -Key $primaryKey
Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId $containerName
The only way to do this is to call Cosmos DB using it's REST API from PowerShell. The link will take you to samples that show simple point operations. You will need to reference the REST API for query here.
Another option may be to explore creating a custom cmdlet where you can use the Cosmos DB .NET SDK to query your data then return via your custom cmdlet.
The Cosmos DB PowerShell module from the gallery works great for that.
$cosmosDBAccountName = "..."
$cosmosDBDatabaseName = "..."
$cosmosDBContainerName = "..."
# First get your account key
$cosmosDBAccountKey = Get-AzCosmosDBAccountKey -ResourceGroupName $rgName -Name $cosmosDBAccountName
# Then establish a context
$primaryKey = ConvertTo-SecureString -String $cosmosDBAccountKey -AsPlainText -Force
$cosmosDbContext = New-CosmosDbContext -Account $cosmosDBAccountName -Database $cosmosDBDatabaseName -Key $primaryKey
# Finally issue your query
$query = "SELECT * FROM customers c WHERE c.deviceid = '0' ORDER BY c.windowend DESC"
(Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId $cosmosDBContainerName -Query $query) | Select-Object {$_.deviceid,$_.jobname}