Connection string and account key operations for an Azure Cosmos account using PowerShell

Note

This article has been updated to use the new Azure PowerShell Az module. You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. For Az module installation instructions, see Install Azure PowerShell.

This sample requires Azure PowerShell Az 1.0 or later. Run Get-Module -ListAvailable Az to see which versions are installed. If you need to install, see Install Azure PowerShell module.

Run Connect-AzAccount to sign in to Azure.

Sample script

This samples requires the resource group and account to exist. Use an existing PowerShell create sample to provision an account first.

# Account keys and connection string operations for Azure Cosmos account

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$keyKind = @{ "keyKind"="Primary" }


Read-Host -Prompt "List connection strings for an Azure Cosmos Account"

Invoke-AzResourceAction -Action listConnectionStrings `
    -ResourceType "Microsoft.DocumentDb/databaseAccounts" -ApiVersion "2015-04-08" `
    -ResourceGroupName $resourceGroupName -Name $accountName | Select-Object *

Read-Host -Prompt "List keys for an Azure Cosmos Account"

Invoke-AzResourceAction -Action listKeys `
    -ResourceType "Microsoft.DocumentDb/databaseAccounts" -ApiVersion "2015-04-08" `
    -ResourceGroupName $resourceGroupName -Name $accountName | Select-Object *

Read-Host -Prompt "Regenerate the primary key for an Azure Cosmos Account"

$keys = Invoke-AzResourceAction -Action regenerateKey `
    -ResourceType "Microsoft.DocumentDb/databaseAccounts" -ApiVersion "2015-04-08" `
    -ResourceGroupName $resourceGroupName -Name $accountName -Parameters $keyKind

Write-Host $keys

Clean up deployment

After the script sample has been run, the following command can be used to remove the resource group and all resources associated with it.

Remove-AzResourceGroup -ResourceGroupName "myResourceGroup"

Script explanation

This script uses the following commands. Each command in the table links to command specific documentation.

Command Notes
Azure Resources
Invoke-AzResourceAction Invokes an action on a resource.
Azure Resource Groups
Remove-AzResourceGroup Deletes a resource group including all nested resources.

Next steps

For more information on the Azure PowerShell, see Azure PowerShell documentation.

Additional Azure Cosmos DB PowerShell script samples can be found in the Azure Cosmos DB PowerShell scripts.