{"id":13623211,"url":"https://github.com/PlagueHO/CosmosDB","last_synced_at":"2025-04-15T14:32:21.843Z","repository":{"id":26443106,"uuid":"108381675","full_name":"PlagueHO/CosmosDB","owner":"PlagueHO","description":"PowerShell Module for working with Azure Cosmos DB databases, collections, documents, attachments, offers, users, permissions, triggers, stored procedures and user defined functions.","archived":false,"fork":false,"pushed_at":"2024-10-18T07:55:04.000Z","size":2097,"stargazers_count":154,"open_issues_count":73,"forks_count":46,"subscribers_count":8,"default_branch":"main","last_synced_at":"2024-10-30T04:50:23.759Z","etag":null,"topics":["azure","cosmosdb","documentdb","powershell","powershell-module","restapi"],"latest_commit_sha":null,"homepage":"http://dscottraynsford.com","language":"PowerShell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PlagueHO.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-26T08:15:27.000Z","updated_at":"2024-10-18T07:09:44.000Z","dependencies_parsed_at":"2023-02-16T16:20:27.375Z","dependency_job_id":"3b0563f2-5b3c-46bc-87b3-9fe2f51a323d","html_url":"https://github.com/PlagueHO/CosmosDB","commit_stats":null,"previous_names":[],"tags_count":116,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PlagueHO%2FCosmosDB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PlagueHO%2FCosmosDB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PlagueHO%2FCosmosDB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PlagueHO%2FCosmosDB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PlagueHO","download_url":"https://codeload.github.com/PlagueHO/CosmosDB/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223677487,"owners_count":17184482,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azure","cosmosdb","documentdb","powershell","powershell-module","restapi"],"created_at":"2024-08-01T21:01:29.211Z","updated_at":"2025-04-15T14:32:21.832Z","avatar_url":"https://github.com/PlagueHO.png","language":"PowerShell","funding_links":[],"categories":["PowerShell","Libraries"],"sub_categories":["Powershell"],"readme":"[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/PlagueHO/CosmosDB/blob/dev/LICENSE)\r\n[![Documentation](https://img.shields.io/badge/Docs-CosmosDB-blue.svg)](https://github.com/PlagueHO/CosmosDB/wiki)\r\n[![PowerShell Gallery](https://img.shields.io/badge/PowerShell%20Gallery-CosmosDB-blue.svg)](https://www.powershellgallery.com/packages/CosmosDB)\r\n[![PowerShell Gallery](https://img.shields.io/powershellgallery/dt/cosmosdb.svg)](https://www.powershellgallery.com/packages/CosmosDB)\r\n[![Minimum Supported Windows PowerShell Version](https://img.shields.io/badge/WindowsPowerShell-5.1-blue.svg)](https://github.com/PlagueHO/CosmosDB)\r\n[![Minimum Supported PowerShell Core Version](https://img.shields.io/badge/PSCore-6.0-blue.svg)](https://github.com/PlagueHO/CosmosDB)\r\n[![Minimum Supported PowerShell Version](https://img.shields.io/badge/PS-7.0-blue.svg)](https://github.com/PlagueHO/CosmosDB)\r\n\r\n# CosmosDB PowerShell Module\r\n\r\n## Module Build Status\r\n\r\n| Branch | Azure Pipelines                    | Automated Tests                    | Code Quality                       |\r\n| ------ | ---------------------------------- | -----------------------------------| ---------------------------------- |\r\n| main   | [![ap-image-main][]][ap-site-main] | [![ts-image-main][]][ts-site-main] | [![cq-image-main][]][cq-site-main] |\r\n\r\n## Table of Contents\r\n\r\n- [Introduction](#introduction)\r\n- [Requirements](#requirements)\r\n- [Recommended Knowledge](#recommended-knowledge)\r\n- [Installation](#installation)\r\n- [Getting Started](#getting-started)\r\n  - [Working with Contexts](#working-with-contexts)\r\n    - [Create a Context using an Entra ID Authorization Token](create-a-context-using-an-entra-id-authorization-token)\r\n      - [Configuring Role-Based Access Control (RBAC) with Entra ID](#configuring-role-based-access-control-rbac-with-entra-id)\r\n      - [Database Operations allowed by Role-Based Access Control](#database-operations-allowed-by-role-based-access-control)\r\n    - [Create a Context specifying the Key Manually](#create-a-context-specifying-the-key-manually)\r\n    - [Use CosmosDB Module to Retrieve Key from Azure Management Portal](#use-cosmosdb-module-to-retrieve-key-from-azure-management-portal)\r\n    - [Create a Context from Resource Authorization Tokens](#create-a-context-from-resource-authorization-tokens)\r\n    - [Create a Context for a Cosmos DB in Azure US Government Cloud](#create-a-context-for-a-cosmos-db-in-azure-us-government-cloud)\r\n    - [Create a Context for a Cosmos DB in Azure China Cloud (Mooncake)](#create-a-context-for-a-cosmos-db-in-azure-china-cloud-mooncake)\r\n    - [Create a Context for a Cosmos DB with a Custom Endpoint](#create-a-context-for-a-cosmos-db-with-a-custom-endpoint)\r\n    - [Create a Context for a Cosmos DB Emulator](#create-a-context-for-a-cosmos-db-emulator)\r\n  - [Working with Accounts](#working-with-accounts)\r\n  - [Working with Databases](#working-with-databases)\r\n  - [Working with Offers](#working-with-offers)\r\n  - [Working with Collections](#working-with-collections)\r\n    - [Creating a Collection with a custom Indexing Policy](#creating-a-collection-with-a-custom-indexing-policy)\r\n    - [Creating a Collection with a custom Indexing Policy including Composite Indexes](#creating-a-collection-with-a-custom-indexing-policy-including-composite-indexes)\r\n    - [Update an existing Collection with a new Indexing Policy](#update-an-existing-collection-with-a-new-indexing-policy)\r\n    - [Creating a Collection with a custom Indexing Policy using JSON](#creating-a-collection-with-a-custom-indexing-policy-using-JSON)\r\n    - [Creating a Collection with a custom Unique Key Policy](#creating-a-collection-with-a-custom-unique-key-policy)\r\n    - [Update an existing Collection with a new Unique Key Policy](#update-an-existing-collection-with-a-new-unique-key-policy)\r\n    - [Creating a Collection without a Partition Key](#creating-a-collection-without-a-partition-key)\r\n  - [Working with Documents](#working-with-documents)\r\n    - [Using a While Loop to get all Documents in a Collection](#using-a-while-loop-to-get-all-documents-in-a-collection)\r\n    - [Working with Documents in a non-partitioned Collection](#working-with-documents-in-a-non-partitioned-collection)\r\n  - [Using Resource Authorization Tokens](#using-resource-authorization-tokens)\r\n  - [Working with Attachments](#working-with-attachments)\r\n  - [Working with Users](#working-with-users)\r\n  - [Stored Procedures](#working-with-stored-procedures)\r\n  - [Working with Triggers](#working-with-triggers)\r\n  - [Working with User Defined Functions](#working-with-user-defined-functions)\r\n  - [How to Handle Exceeding Provisioned Throughput](#how-to-handle-exceeding-provisioned-throughput)\r\n- [Compatibility and Testing](#compatibility-and-testing)\r\n- [Contributing](#contributing)\r\n- [Cmdlets](#cmdlets)\r\n- [Change Log](#change-log)\r\n- [Links](#links)\r\n\r\n## Introduction\r\n\r\nThis PowerShell module provides cmdlets for working with Azure Cosmos DB.\r\n\r\nThe _CosmosDB PowerShell module_ enables management of:\r\n\r\n- [Attachments](#working-with-attachments)\r\n- [Collections](#working-with-collections)\r\n- [Databases](#working-with-databases)\r\n- [Documents](#working-with-documents)\r\n- [Offers](#working-with-offers)\r\n- [Permissions](#working-with-permissions)\r\n- [Stored Procedures](#working-with-stored-procedures)\r\n- [Triggers](#working-with-triggers)\r\n- [User Defined Functions](#working-with-user-defined-functions)\r\n- [Users](#working-with-users)\r\n\r\nThe module uses the Cosmos DB (DocumentDB) Rest APIs.\r\n\r\nFor more information on the Cosmos DB Rest APIs, see [this link](https://docs.microsoft.com/rest/api/documentdb/restful-interactions-with-documentdb-resources).\r\n\r\n## Requirements\r\n\r\nThis module requires the following:\r\n\r\n- Windows PowerShell 5.x, PowerShell Core 6.x or PowerShell 7.x\r\n\r\n### PowerShell Module Dependencies\r\n\r\n- **Az.Account**: v2.19.0 or newer.\r\n- **Az.Resources**: 6.16.2 or newer.\r\n\r\nThese modules are required if using `New-CosmosDbContext -ResourceGroupName $resourceGroup`\r\nor `*-CosmosDbAccount` functions.\r\n\r\n## Recommended Knowledge\r\n\r\nIt is recommended that before using this module it is important to understand\r\nthe fundamental concepts of Cosmos DB. This will ensure you have an optimal\r\nexperience by adopting design patterns that align to Cosmos DB best practice.\r\n\r\nUsers new to Cosmos DB should familiarize themselves with the following\r\nconcepts:\r\n\r\n- [Overview of Cosmos DB](https://docs.microsoft.com/bs-cyrl-ba/azure/cosmos-db/introduction)\r\n- [NoSQL vs. Relational Databases](https://docs.microsoft.com/bs-cyrl-ba/azure/cosmos-db/relational-nosql)\r\n- [Partitioning](https://docs.microsoft.com/bs-cyrl-ba/azure/cosmos-db/partitioning-overview)\r\n\r\nIt is also recommended to watch [this Ignite video](https://myignite.microsoft.com/sessions/1410edb6-204d-4c45-adbb-ccb49e8135cf?source=sessions)\r\non data modelling and partitioning in Cosmos DB.\r\n\r\n## Installation\r\n\r\nTo install the module from PowerShell Gallery, use the PowerShell Cmdlet:\r\n\r\n```powershell\r\nInstall-Module -Name CosmosDB\r\n```\r\n\r\n## Getting Started\r\n\r\nThe easiest way to use this module is to first create a context\r\nobject using the `New-CosmosDbContext` cmdlet which you can then\r\nuse to pass to the other Cosmos DB cmdlets in the module.\r\n\r\nTo create the context object you will either need access to the\r\nprimary or secondary keys from your Cosmos DB account or allow\r\nthe _CosmosDB Powershell module_ to retrieve the keys directly from\r\nthe Azure management portal for you.\r\n\r\n### Working with Contexts\r\n\r\n#### Create a Context Using an Entra ID Authorization Token\r\n\r\nYou can create a context object that can include use an _Entra ID Authorization Token_\r\nthat will be used to authenticate requests to Cosmos DB.\r\n\r\n\u003e Important: This is a recommended security practice to use when you've\r\n\u003e [configured role-based access control with Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac)\r\n\u003e on your Azure Cosmos DB account. It will help you keep your account secure\r\n\u003e by not exposing the primary or secondary keys in your code.\r\n\r\nTo create a context object using an _Entra ID Authorization Token_ you will need\r\nto set the `EntraIdToken` parameter to the token you have retrieved from Entra ID\r\nfor the identity that you have given appropriate permissions to the `account`,\r\n`database` and/or `collection`. See [this page](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac#concepts) for more information.\r\n\r\n```powershell\r\n# Get an OAuth2 resource token from Entra ID for the Cosmos DB account.\r\n# This will use the currently logged in user to authenticate to Entra ID to\r\n# get the token. There are many other ways of doing this.\r\n$entraIdOAuthToken = Get-CosmosDbEntraIdToken -Endpoint 'https://MyAzureCosmosDB.documents.azure.com'\r\n\r\n$newCosmosDbContextParams  = @{\r\n    Account      = 'MyAzureCosmosDB'\r\n    EntraIdToken = $entraIdOAuthToken\r\n}\r\n$accountContext = New-CosmosDbContext @newCosmosDbContextParams\r\nGet-CosmosDbCollection -Context $accountContext -Id MyNewCollection\r\n```\r\n\r\nAn alternate method is to allow the New-CosmosDbContext cmdlet to retrieve the\r\nEntra ID token for you. This will require you to have already logged into Azure\r\nand will use the base URI detected for the account as the resource URI for the\r\ntoken request.\r\n\r\n```powershell\r\n$newCosmosDbContextParams  = @{\r\n    Account      = 'MyAzureCosmosDB'\r\n    AutoGenerateEntraIdToken = $true\r\n}\r\n$accountContext = New-CosmosDbContext @newCosmosDbContextParams\r\nGet-CosmosDbCollection -Context $accountContext -Id MyNewCollection\r\n```\r\n\r\n\u003e Important: Using an Entra ID Authorization Token is only supported by setting it\r\n\u003e in a CosmosDB.Context object and passing that to the commands you want to execute.\r\n\u003e Not all commands support this method of authentication. If you need to use a command\r\n\u003e that doesn't support this method of authentication, you will need to use one of the\r\n\u003e other methods of authentication. See the [Database Operations allowed by Role-Based Access Control](#database-operations-allowed-by-role-based-access-control)\r\n\u003e section for more information.\r\n\r\n##### Configuring Role-Based Access Control (RBAC) with Entra ID\r\n\r\nThere are several ways to configure a Cosmos DB Account with Role-Based Access Control,\r\nincluding:\r\n\r\n - *Azure Bicep*: An example can be found in the [\\tests\\TestHelper\\AzureDeploy\\CosmosDb.bicep](\\tests\\TestHelper\\AzureDeploy\\CosmosDb.bicep) file.\r\n - *Azure PowerShell*: The integration tests use this method.\r\n - *AzCli*.\r\n\r\n\u003e Important Note: One thing I found when adding a SQL Role Assignment to the Cosmos DB\r\n\u003e Account (or Database or Container) is that the principal ID must be the Object ID of\r\n\u003e the user, group or service principal that you want to assign the role to. You can't use\r\n\u003e the Application ID for this value.\r\n\r\nFor more information on how to configure Role-Based Access Control with Entra ID, see the\r\n[Configure role-based access control with Microsoft Entra ID for your Azure Cosmos DB account](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac)\r\npage.\r\n\r\n##### Database Operations allowed by Role-Based Access Control\r\n\r\nOnly a subset of all the operations that can be performed on a Cosmos DB account are\r\nallowed by Role-Based Access Control. The following operations are allowed:\r\nThis permission model covers only database operations that involve reading and writing data. It does not cover any kind of management operations on management resources, including:\r\n\r\n- Create/Replace/Delete Database\r\n- Create/Replace/Delete Container\r\n- Read/Replace Container Throughput\r\n- Create/Replace/Delete/Read Stored Procedures\r\n- Create/Replace/Delete/Read Triggers\r\n- Create/Replace/Delete/Read User Defined Functions\r\n\r\nFor more information on this, please see the [Role-based access control (RBAC) with Azure Cosmos DB](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-setup-rbac#permission-model) page.\r\n\r\n#### Create a Context specifying the Key Manually\r\n\r\n\u003e Note: This method of authenticating to Cosmos DB is not recommended for\r\n\u003e production use. It is recommended to use the _Entra ID Authorization Token_\r\n\u003e method described above.\r\n\r\nFirst convert your key into a secure string:\r\n\r\n```powershell\r\n$primaryKey = ConvertTo-SecureString -String 'GFJqJesi2Rq910E0G7P4WoZkzowzbj23Sm9DUWFX0l0P8o16mYyuaZBN00Nbtj9F1QQnumzZKSGZwknXGERrlA==' -AsPlainText -Force\r\n```\r\n\r\nUse the key secure string, Azure Cosmos DB account name and database to\r\ncreate a context variable:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -Key $primaryKey\r\n```\r\n\r\n#### Use CosmosDB Module to Retrieve Key from Azure Management Portal\r\n\r\n\u003e Note: This method of authenticating to Cosmos DB is not recommended for\r\n\u003e production use. It is recommended to use the _Entra ID Authorization Token_\r\n\u003e method described above.\r\n\r\nTo create a context object so that the _CosmosDB PowerShell module_\r\nretrieves the primary or secondary key from the Azure Management\r\nPortal, use the following command:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -ResourceGroupName MyCosmosDbResourceGroup -MasterKeyType SecondaryMasterKey\r\n```\r\n\r\n_Note: if PowerShell is not connected to Azure then an interactive\r\nAzure login will be initiated. If PowerShell is already connected to\r\nan account that doesn't contain the Cosmos DB you wish to connect to then\r\nyou will first need to connect to the correct account using the\r\n`Connect-AzAccount` cmdlet._\r\n\r\n#### Create a Context from Resource Authorization Tokens\r\n\r\n\u003e Note: This method of authenticating to Cosmos DB is better than using master key\r\n\u003e authentication, as it provides the ability to limit access to specific resources.\r\n\u003e However, it is recommended to use the _Entra ID Authorization Token_ method\r\n\u003e described above if possible.\r\n\r\nSee the section [Using Resource Authorization Tokens](#using-resource-authorization-tokens)\r\nfor instructions on how to create a Context object containing one or more _Resource\r\nAuthorization Tokens_.\r\n\r\n#### Create a Context for a Cosmos DB in Azure US Government Cloud\r\n\r\n\u003e Note: This method of authenticating to Cosmos DB is not recommended for\r\n\u003e production use. It is recommended to use the _Entra ID Authorization Token_\r\n\u003e method described above.\r\n\r\nUse the key secure string, Azure Cosmos DB account name and database to\r\ncreate a context variable and set the `Environment` parameter to\r\n`AzureUSGovernment`:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -Key $primaryKey -Environment AzureUSGovernment\r\n```\r\n\r\n#### Create a Context for a Cosmos DB in Azure China Cloud (Mooncake)\r\n\r\n\u003e Note: This method of authenticating to Cosmos DB is not recommended for\r\n\u003e production use. It is recommended to use the _Entra ID Authorization Token_\r\n\u003e method described above.\r\n\r\nUse the key secure string, Azure Cosmos DB account name and database to\r\ncreate a context variable and set the `Environment` parameter to\r\n`AzureChinaCloud`:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -Key $primaryKey -Environment AzureChinaCloud\r\n```\r\n\r\n#### Create a Context for a Cosmos DB with a Custom Endpoint\r\n\r\nUse the key secure string, Azure Cosmos DB account name, database and\r\nCosmos DB custom endpoint hostname:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -Key $primaryKey -EndpointHostname documents.eassov.com\r\n```\r\n\r\n#### Create a Context for a Cosmos DB Emulator\r\n\r\nMicrosoft provides a [Cosmos DB emulator](https://docs.microsoft.com/azure/cosmos-db/local-emulator) that\r\nyou can run locally to enable testing and debugging scenarios. To create\r\na context for a Cosmos DB emulator installed on the localhost use the\r\nfollowing command:\r\n\r\n```powershell\r\n$cosmosDbContext = New-CosmosDbContext -Emulator -Database MyDatabase\r\n```\r\n\r\nYou can also provide a custom URI if the emulator is hosted on another\r\nmachine or an alternate port as well as specifying an alternate Key to use:\r\n\r\n```powershell\r\n$primaryKey = ConvertTo-SecureString -String 'GFJqJesi2Rq910E0G7P4WoZkzowzbj23Sm9DUWFX0l0P8o16mYyuaZBN00Nbtj9F1QQnumzZKSGZwknXGERrlA==' -AsPlainText -Force\r\n$cosmosDbContext = New-CosmosDbContext -Emulator -Database MyDatabase -Uri https://cosmosdbemulator.contoso.com:9081 -Key $primaryKey\r\n```\r\n\r\n### Working with Accounts\r\n\r\nYou can create, retrieve, update and remove Azure Cosmos DB accounts using\r\nthis module. To use these features you will need to ensure the **Az.Profile**\r\nand **Az.Resources** modules installed - See [Requirements](#requirements)\r\nabove.\r\n\r\n_Note: You must have first logged PowerShell into Azure using the\r\n`Connect-AzAccount` function before you can use these functions._\r\n\r\nCreate a new Cosmos DB account in Azure:\r\n\r\n```powershell\r\nNew-CosmosDbAccount -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup -Location WestUS\r\n```\r\n\r\nGet the properties of an existing Cosmos DB account in Azure:\r\n\r\n```powershell\r\nGet-CosmosDbAccount -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup\r\n```\r\n\r\nGet a Secure String containing the Primary Master Key for an\r\naccount in Azure:\r\n\r\n```powershell\r\n$key = Get-CosmosDbAccountMasterKey -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup\r\n```\r\n\r\nGet a Secure String containing the Secondary Readonly Master Key for an\r\naccount in Azure:\r\n\r\n```powershell\r\n$key = Get-CosmosDbAccountMasterKey -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup -MasterKeyType SecondaryReadonlyMasterKey\r\n```\r\n\r\nRegenerate the Primary Readonly Master Key for an account in Azure:\r\n\r\n```powershell\r\nNew-CosmosDbAccountMasterKey -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup -MasterKeyType PrimaryReadonlyMasterKey\r\n```\r\n\r\nGet the connection strings used to connect to an existing Cosmos DB\r\naccount in Azure:\r\n\r\n\u003e Note: This function is not currently working due to an issue in the Microsoft/DocumentDB\r\n\u003e Provider. See [this issue](https://github.com/Azure/azure-powershell/issues/3650) for more information.\r\n\r\n```powershell\r\nGet-CosmosDbAccountConnectionString -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup\r\n```\r\n\r\nUpdate an existing Cosmos DB account in Azure:\r\n\r\n```powershell\r\nSet-CosmosDbAccount -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup -Location WestUS -DefaultConsistencyLevel Strong\r\n```\r\n\r\nDelete an existing Cosmos DB account in Azure:\r\n\r\n```powershell\r\nRemove-CosmosDbAccount -Name MyAzureCosmosDB -ResourceGroupName MyCosmosDbResourceGroup\r\n```\r\n\r\n### Working with Databases\r\n\r\nCreate a new database in the Cosmos DB account with database throughput\r\nprovisioned at 1200 RU/s:\r\n\r\n```powershell\r\nNew-CosmosDbDatabase -Context $cosmosDbContext -Id MyDatabase -OfferThroughput 1200\r\n```\r\n\r\nCreate a new database in the Cosmos DB account with autoscaling throughput\r\nwith a maximum of 40,000 RU/s down to a minimum of 4,000 RU/s:\r\n\r\n```powershell\r\nNew-CosmosDbDatabase -Context $cosmosDbContext -Id MyDatabase -AutoscaleThroughput 40000\r\n```\r\n\r\nCreate a new database in the Cosmos DB account that will have throughput\r\nprovisioned at the collection rather than the database:\r\n\r\n```powershell\r\nNew-CosmosDbDatabase -Context $cosmosDbContext -Id DatabaseWithCollectionThroughput\r\n```\r\n\r\nGet a list of databases in the Cosmos DB account:\r\n\r\n```powershell\r\nGet-CosmosDbDatabase -Context $cosmosDbContext\r\n```\r\n\r\nGet the specified database from the Cosmos DB account:\r\n\r\n```powershell\r\nGet-CosmosDbDatabase -Context $cosmosDbContext -Id MyDatabase\r\n```\r\n\r\n### Working with Offers\r\n\r\nGet a list of offers in the Cosmos DB account:\r\n\r\n```powershell\r\nGet-CosmosDbOffer -Context $cosmosDbContext\r\n```\r\n\r\nQuery the offers in the Cosmos DB account:\r\n\r\n```powershell\r\nGet-CosmosDbOffer -Context $cosmosDbContext -Query 'SELECT * FROM root WHERE (root[\"id\"] = \"lyiu\")'\r\n```\r\n\r\nUpdate an existing V2 offer to set a different throughput:\r\n\r\n```powershell\r\nGet-CosmosDbOffer -Context $cosmosDbContext -Id lyiu |\r\n    Set-CosmosDbOffer -Context $cosmosDbContext -OfferThroughput 1000 -OfferIsRUPerMinuteThroughputEnabled $true\r\n```\r\n\r\nUpdate all existing V2 offers to set a different throughput:\r\n\r\n```powershell\r\nGet-CosmosDbOffer -Context $cosmosDbContext -Query 'SELECT * FROM root WHERE (root[\"offerVersion\"] = \"V2\")' |\r\n    Set-CosmosDbOffer -Context $cosmosDbContext -OfferThroughput 10000 -OfferIsRUPerMinuteThroughputEnabled $false\r\n```\r\n\r\n### Working with Collections\r\n\r\nGet a list of collections in a database:\r\n\r\n```powershell\r\nGet-CosmosDbCollection -Context $cosmosDbContext\r\n```\r\n\r\nCreate a collection in the database with the partition key 'id' and\r\nthe offer throughput of 50,000 RU/s:\r\n\r\n```powershell\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -OfferThroughput 50000\r\n```\r\n\r\nCreate a collection in the database with the partition key 'id' using\r\nautoscaling with the maximum throughput of 40,000 RU/s and a minimum of\r\n4,000 RU/s:\r\n\r\n```powershell\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -AutoscaleThroughput 40000\r\n```\r\n\r\nGet a specified collection from a database:\r\n\r\n```powershell\r\nGet-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection\r\n```\r\n\r\nGet the first 5 collections from a database with a continuation token to\r\nallow retrieval of further collections:\r\n\r\n```powershell\r\n$ResponseHeader = $null\r\n$collections = Get-CosmosDbCollection -Context $cosmosDbContext -MaxItemCount 5 -ResponseHeader ([ref] $ResponseHeader)\r\n$continuationToken = Get-CosmosDbContinuationToken -ResponseHeader $ResponseHeader\r\n```\r\n\r\nGet the next 5 collections from a database using a continuation token:\r\n\r\n```powershell\r\n$collections = Get-CosmosDbCollection -Context $cosmosDbContext -MaxItemCount 5 -ContinuationToken $continuationToken\r\n```\r\n\r\nDelete a collection from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection\r\n```\r\n\r\n#### Creating a Collection with a custom Indexing Policy\r\n\r\nYou can create a collection with a custom indexing policy by assembling\r\nan Indexing Policy object using the functions:\r\n\r\n- `New-CosmosDbCollectionCompositeIndexElement`\r\n- `New-CosmosDbCollectionIncludedPathIndex`\r\n- `New-CosmosDbCollectionIncludedPath`\r\n- `New-CosmosDbCollectionExcludedPath`\r\n- `New-CosmosDbCollectionIndexingPolicy`\r\n\r\nFor example, to create a string range, a number range index and a point\r\nspatial index on the '/*' path using consistent indexing mode with no\r\nexcluded paths:\r\n\r\n```powershell\r\n$indexStringRange = New-CosmosDbCollectionIncludedPathIndex -Kind Range -DataType String\r\n$indexNumberRange = New-CosmosDbCollectionIncludedPathIndex -Kind Range -DataType Number\r\n$indexPointSpatial = New-CosmosDbCollectionIncludedPathIndex -Kind Spatial -DataType Point\r\n$indexIncludedPath = New-CosmosDbCollectionIncludedPath -Path '/*' -Index $indexStringRange, $indexNumberRange, $indexPointSpatial\r\n$indexingPolicy = New-CosmosDbCollectionIndexingPolicy -Automatic $true -IndexingMode Consistent -IncludedPath $indexIncludedPath\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -IndexingPolicy $indexingPolicy\r\n```\r\n\r\n\u003e **Important Index Notes**\r\n\u003e\r\n\u003e The _Hash_ index Kind is no longer supported by Cosmos DB.\r\n\u003e A warning will be displayed if the Hash index Kind is used.\r\n\u003e The Hash index Kind will be removed in a future BREAKING release of the Cosmos\r\n\u003e DB module.\r\n\u003e See [this page](https://docs.microsoft.com/azure/cosmos-db/index-types#index-kind)\r\n\u003e for more information.\r\n\u003e\r\n\u003e The _Precision_ parameter is no longer supported by Cosmos DB and will be\r\n\u003e ignored. The maximum precision of -1 will always be used for Range indexes.\r\n\u003e A warning will be displayed if the Precision parameter is passed.\r\n\u003e The Precision parameter will be removed in a future BREAKING release of the\r\n\u003e Cosmos DB module.\r\n\u003e See [this page](https://docs.microsoft.com/azure/cosmos-db/index-types#index-precision)\r\n\u003e for more information.\r\n\u003e\r\n\u003e It is recommended to remove the use of the _Hash_ index Kind and any instances\r\n\u003e of the _Precision_ parameter and any automation or scripts to avoid being affected\r\n\u003e by future BREAKING CHANGES.\r\n\r\nFor more information on how Cosmos DB indexes documents, see [this page](https://docs.microsoft.com/azure/cosmos-db/indexing-policies).\r\n\r\n#### Creating a Collection with a custom Indexing Policy including Composite Indexes\r\n\r\nTo create a custom indexing policy that automatically indexes all paths but\r\nalso includes two composite indexes, each consisting of two paths:\r\n\r\n```powershell\r\n$compositeIndex = @(\r\n    @(\r\n        (New-CosmosDbCollectionCompositeIndexElement -Path /name -Order Ascending ),\r\n        (New-CosmosDbCollectionCompositeIndexElement -Path /age -Order Ascending )\r\n    ),\r\n    @(\r\n        (New-CosmosDbCollectionCompositeIndexElement -Path /name -Order Ascending ),\r\n        (New-CosmosDbCollectionCompositeIndexElement -Path /age -Order Descending )\r\n    )\r\n)\r\n$indexIncludedPath = New-CosmosDbCollectionIncludedPath -Path '/*'\r\n$indexingPolicy = New-CosmosDbCollectionIndexingPolicy -Automatic $true -IndexingMode Consistent -IncludedPath $indexIncludedPath -CompositeIndex $compositeIndex\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -IndexingPolicy $indexingPolicy\r\n```\r\n\r\n#### Update an existing Collection with a new Indexing Policy\r\n\r\nYou can update an existing collection with a custom indexing policy by\r\nassembling an Indexing Policy using the method in the previous section\r\nand then applying it using the `Set-CosmosDbCollection` function:\r\n\r\n```powershell\r\n$indexStringRange = New-CosmosDbCollectionIncludedPathIndex -Kind Range -DataType String\r\n$indexIncludedPath = New-CosmosDbCollectionIncludedPath -Path '/*' -Index $indexStringRange\r\n$indexingPolicy = New-CosmosDbCollectionIndexingPolicy -Automatic $true -IndexingMode Consistent -IncludedPath $indexIncludedPath\r\nSet-CosmosDbCollection -Context $cosmosDbContext -Id MyExistingCollection -IndexingPolicy $indexingPolicy\r\n```\r\n\r\nAfter updating a collection with an indexing policy it will take some\r\ntime to transform the index. To retrieve the progress of the index\r\ntransformation, call the `Get-CosmosDbCollection` function and then\r\nevaluate the value of the\r\n\r\n```powershell\r\nPS C:\\\u003e $ResponseHeader = $null\r\nPS C:\\\u003e $collections = Get-CosmosDbCollection -Context $cosmosDbContext -Id MyExistingCollection -ResponseHeader ([ref] $ResponseHeader)\r\nPS C:\\\u003e $indexUpdateProgress = Get-CosmosDbResponseHeaderAttribute -ResponseHeader $ResponseHeader -HeaderName x-ms-documentdb-collection-index-transformation-progress\r\n```\r\n\r\n#### Creating a Collection with a custom Indexing Policy using JSON\r\n\r\nIf the `New-CosmosDbCollection*` functions don't enable you to build\r\nthe index policy to your requirements, you can also pass the raw index\r\npolicy JSON to the function using the `IndexingPolicyJson` parameter:\r\n\r\n```powershell\r\n$indexingPolicyJson = @'\r\n{\r\n    \"automatic\":true,\r\n    \"indexingMode\":\"Consistent\",\r\n    \"includedPaths\":[\r\n        {\r\n            \"path\":\"/*\"\r\n        }\r\n    ],\r\n    \"excludedPaths\":[],\r\n    \"compositeIndexes\":[\r\n        [\r\n            {\r\n                \"path\":\"/name\",\r\n                \"order\":\"ascending\"\r\n            },\r\n            {\r\n                \"path\":\"/age\",\r\n                \"order\":\"descending\"\r\n            }\r\n        ]\r\n    ]\r\n}\r\n'@\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -IndexingPolicyJson $indexingPolicyJson\r\n```\r\n\r\n#### Creating a Collection with a custom Unique Key Policy\r\n\r\nYou can create a collection with a custom unique key policy by assembling\r\na Unique Key Policy object using the functions:\r\n\r\n- `New-CosmosDbCollectionUniqueKey`\r\n- `New-CosmosDbCollectionUniqueKeyPolicy`\r\n\r\nFor example, to create a unique key policy that contains two unique keys,\r\nwith the first unique key combining '/name' and '/address' and the second\r\nunique key is set to '/email'.\r\n\r\n```powershell\r\n$uniqueKeyNameAddress = New-CosmosDbCollectionUniqueKey -Path /name, /address\r\n$uniqueKeyEmail = New-CosmosDbCollectionUniqueKey -Path /email\r\n$uniqueKeyPolicy = New-CosmosDbCollectionUniqueKeyPolicy -UniqueKey $uniqueKeyNameAddress, $uniqueKeyEmail\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id MyNewCollection -PartitionKey id -UniqueKeyPolicy $uniqueKeyPolicy\r\n```\r\n\r\nFor more information on how Cosmos DB indexes documents, see [this page](https://docs.microsoft.com/azure/cosmos-db/unique-keys).\r\n\r\n#### Update an existing Collection with a new Unique Key Policy\r\n\r\nYou can update an existing collection with a custom unique key policy by\r\nassembling a Unique Key Policy using the method in the previous section\r\nand then applying it using the `Set-CosmosDbCollection` function:\r\n\r\n```powershell\r\n$uniqueKeyNameAddress = New-CosmosDbCollectionUniqueKey -Path /name, /address\r\n$uniqueKeyEmail = New-CosmosDbCollectionUniqueKey -Path /email\r\n$uniqueKeyPolicy = New-CosmosDbCollectionUniqueKeyPolicy -UniqueKey $uniqueKeyNameAddress, $uniqueKeyEmail\r\nSet-CosmosDbCollection -Context $cosmosDbContext -Id MyExistingCollection -IndexingPolicy $indexingPolicy\r\n```\r\n\r\n#### Creating a Collection without a Partition Key\r\n\r\n\u003e **Warning:** It is not recommended to create a collection without a partition\r\nkey. It may result in reduced performance and increased cost. This\r\nfunctionality is included for backwards compatibility only.\r\n\r\nIt is only possible to create non-partitioned collection in a database that has\r\nnot got provisioned throughput at the database level enabled.\r\n\r\nCreate a collection in the database with the offer throughput of 2500 RU/s\r\nand without a partition key:\r\n\r\n```powershell\r\nNew-CosmosDbCollection -Context $cosmosDbContext -Id NonPartitionedCollection -OfferThroughput 2500\r\n```\r\n\r\n### Working with Documents\r\n\r\nCreate 10 new documents in a collection in the database using the `id` as\r\nthe partition key:\r\n\r\n```powershell\r\n0..9 | Foreach-Object {\r\n    $id = $([Guid]::NewGuid().ToString())\r\n    $document = @{\r\n        id      = $id\r\n        content = \"Some string\"\r\n        more    = \"Some other string\"\r\n    } | ConvertTo-Json\r\n    New-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentBody $document -PartitionKey $id\r\n}\r\n```\r\n\r\nCreate a new document containing non-ASCII characters in a collection in the\r\ndatabase using the `id` as the partition key:\r\n\r\n```powershell\r\n$id = $([Guid]::NewGuid().ToString())\r\n$document = @{\r\n    id      = $id\r\n    content = \"杉本 司\"\r\n} | ConvertTo-Json\r\nNew-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentBody $document -Encoding 'UTF-8' -PartitionKey $id\r\n```\r\n\r\nReturn a document with a specific Id from a collection in the database using\r\nthe document ID as the partition key:\r\n\r\n```powershell\r\nGet-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -Id $documents[0].id -PartitionKey $documents[0].id\r\n```\r\n\r\n\u003e **Note:** Because this is a partitioned collection, if you don't specify a partition\r\nkey you will receive a `(400) Bad Request` exception.\r\n\r\nGet the first 5 documents from the collection in the database:\r\n\r\n```powershell\r\n$ResponseHeader = $null\r\n$documents = Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -MaxItemCount 5 -ResponseHeader ([ref] $ResponseHeader)\r\n$continuationToken = Get-CosmosDbContinuationToken -ResponseHeader $ResponseHeader\r\n```\r\n\r\n\u003e **Note:** You don't need to specify the partition key here because you are just\r\ngetting the first 5 documents in whatever order they are available so going to\r\na specific partition is not required.\r\n\r\nGet the next 5 documents from a collection in the database using\r\nthe continuation token found in the headers from the previous\r\nrequest:\r\n\r\n```powershell\r\n$documents = Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -MaxItemCount 5 -ContinuationToken $continuationToken\r\n```\r\n\r\nReplace the content of a document in a collection in the database:\r\n\r\n```powershell\r\n$newDocument = @{\r\n    id      = $documents[0].id\r\n    content = \"New string\"\r\n    more    = \"Another new string\"\r\n} | ConvertTo-Json\r\nSet-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -Id $documents[0].id -DocumentBody $newDocument -PartitionKey $documents[0].id\r\n```\r\n\r\nQuerying a collection in a database:\r\n\r\n```powershell\r\n$query = \"SELECT * FROM customers c WHERE (c.id = 'user@contoso.com')\"\r\nGet-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -Query $query\r\n```\r\n\r\nQuerying a collection in a database using a parameterized query:\r\n\r\n```powershell\r\n$query = \"SELECT * FROM customers c WHERE (c.id = @id)\"\r\n$queryParameters = @(\r\n    @{\r\n        name  = \"@id\"\r\n        value = \"user@contoso.com\"\r\n    }\r\n)\r\nGet-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -Query $query -QueryParameters $queryParameters\r\n```\r\n\r\nDelete a document from a collection in the database:\r\n\r\n```powershell\r\nRemove-CosmosDbDocument -Context $cosmosDbContext -CollectionId MyNewCollection -Id $documents[0].id -PartitionKey $documents[0].id\r\n```\r\n\r\n\u003e **Note:** Because this is a partitioned collection, if you don't specify a partition\r\nkey you will receive a `(400) Bad Request` exception.\r\n\r\n#### Using a While Loop to get all Documents in a Collection\r\n\r\nThe Cosmos DB REST APIs have a maximum response size of 4MB. Therefore, to\r\nget a set of documents from a collection that will be larger than 4MB the\r\nrequest will need to be broken down into blocks using continuation tokens.\r\n\r\nThe following is an example of how that could be implemented.\r\n\r\n```powershell\r\n$documentsPerRequest = 20\r\n$continuationToken = $null\r\n$documents = $null\r\n\r\ndo {\r\n    $responseHeader = $null\r\n    $getCosmosDbDocumentParameters = @{\r\n        Context = $cosmosDbContext\r\n        CollectionId = 'MyNewCollection'\r\n        MaxItemCount = $documentsPerRequest\r\n        ResponseHeader = ([ref] $responseHeader)\r\n    }\r\n\r\n    if ($continuationToken) {\r\n        $getCosmosDbDocumentParameters.ContinuationToken = $continuationToken\r\n    }\r\n\r\n    $documents += Get-CosmosDbDocument @getCosmosDbDocumentParameters\r\n    $continuationToken = Get-CosmosDbContinuationToken -ResponseHeader $responseHeader\r\n} while (-not [System.String]::IsNullOrEmpty($continuationToken))\r\n```\r\n\r\n#### Working with Documents in a non-partitioned Collection\r\n\r\n\u003e **Warning:** It is not recommended to use a collection without a partition\r\nkey. It may result in reduced performance and increased cost. This\r\nfunctionality is included for backwards compatibility only.\r\n\u003e\r\n\u003e Creating a document in a collection that has a Partition Key requires the\r\n`PartitionKey` parameter to be specified for the document:\r\n\r\n```powershell\r\n$document = @{\r\n    id      = \"en-us\"\r\n    locale  = \"English (US)\"\r\n} | ConvertTo-Json\r\nNew-CosmosDbDocument -Context $cosmosDbContext -CollectionId NonPartitionedCollection -DocumentBody $document\r\n```\r\n\r\nGet a document from a partitioned collection with a specific Id:\r\n\r\n```powershell\r\nGet-CosmosDbDocument -Context $cosmosDbContext -CollectionId NonPartitionedCollection -Id 'en-us'\r\n```\r\n\r\nDelete a document from a partitioned collection in the database:\r\n\r\n```powershell\r\nRemove-CosmosDbDocument -Context $cosmosDbContext -CollectionId NonPartitionedCollection -Id 'en-us'\r\n```\r\n\r\n### Working with Attachments\r\n\r\nCreate an attachment on a document in a collection:\r\n\r\n```powershell\r\nNew-CosmosDbAttachment -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentId $documents[0].id -PartitionKey $documents[0].id -Id image_1 -ContentType 'image/jpg' -Media www.bing.com\r\n```\r\n\r\nGet _all_ attachments for a document in a collection:\r\n\r\n```powershell\r\nGet-CosmosDbAttachment -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentId $documents[0].id -PartitionKey $documents[0].id\r\n```\r\n\r\nGet an attachment by Id for a document in a collection:\r\n\r\n```powershell\r\nGet-CosmosDbAttachment -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentId $documents[0].id -PartitionKey $documents[0].id -Id image_1\r\n```\r\n\r\nRename an attachment for a document in a collection:\r\n\r\n```powershell\r\nSet-CosmosDbAttachment -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentId $documents[0].id -PartitionKey $documents[0].id -Id image_1 -NewId image_2\r\n```\r\n\r\nDelete an attachment from a document in collection:\r\n\r\n```powershell\r\nRemove-CosmosDbAttachment -Context $cosmosDbContext -CollectionId MyNewCollection -DocumentId $documents[0].id -PartitionKey $documents[0].id -Id image_2\r\n```\r\n\r\n### Working with Users\r\n\r\nGet a list of users in the database:\r\n\r\n```powershell\r\nGet-CosmosDbUser -Context $cosmosDbContext\r\n```\r\n\r\nCreate a user in the database:\r\n\r\n```powershell\r\nNew-CosmosDbUser -Context $cosmosDbContext -Id dscottraynsford@contoso.com\r\n```\r\n\r\nDelete a user from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbUser -Context $cosmosDbContext -Id dscottraynsford@contoso.com\r\n```\r\n\r\n### Working with Permissions\r\n\r\nGet a list of permissions for a user in the database:\r\n\r\n```powershell\r\nGet-CosmosDbPermission -Context $cosmosDbContext -UserId dscottraynsford@contoso.com\r\n```\r\n\r\nCreate a permission for a user in the database with read access to a collection:\r\n\r\n```powershell\r\n$collectionId = Get-CosmosDbCollectionResourcePath -Database MyDatabase -Id MyNewCollection\r\nNew-CosmosDbPermission -Context $cosmosDbContext -UserId dscottraynsford@contoso.com -Id r_mynewcollection -Resource $collectionId -PermissionMode Read\r\n```\r\n\r\nRemove a permission for a user from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbPermission -Context $cosmosDbContext -UserId dscottraynsford@contoso.com -Id r_mynewcollection\r\n```\r\n\r\n### Using Resource Authorization Tokens\r\n\r\nCosmos DB supports using _resource authorization tokens_ to grant\r\naccess to individual resources (eg. documents, collections, triggers)\r\nto a specific user. A user in this context can also be used to represent\r\nan application that needs access to specific data.\r\nThis can be used to reduce the need to provide access to master keys\r\nto end users.\r\n\r\nTo use a resource authorization token, first a permission must be assigned\r\nto the user for the resource using the `New-CosmosDbPermission`. A user\r\ncan be created using the `New-CosmosDbUser` function.\r\n\r\n**Note: By default, Resource Authorization Tokens expire after an hour.\r\nThis can be extended to a maximum of 5 hours or reduced to minimum of 10\r\nminutes. Use the `TokenExpiry` parameter to control the length of time\r\nthat the resource authorization tokens will be valid for.**\r\n\r\nThe typical pattern for using _resource authorization tokens_ is to\r\nhave a **token broker app** that provides some form of user authentication\r\nand then returns the _resource authorization tokens_ assigned to that\r\nuser. This removes the requirement for the user to be given access to\r\nthe **master** key for the Cosmos DB database.\r\n\r\nFor more information on using _resource authorization tokens_ or the\r\n**token broker app** pattern, please see [this document](https://docs.microsoft.com/azure/cosmos-db/secure-access-to-data#resource-tokens).\r\n\r\nThe following is an example showing how to create a resource context object\r\nthat contains a _resource authorization token_ granting access to read\r\nthe collection `MyNewCollection`. It is assumed that the permission for\r\nthe user `dscottraynsford@contoso.com` has been created as per the\r\nprevious section. The resource context object is then used to retrieve\r\nthe `MyNewCollection`.\r\n\r\nThe _resource authorization token_ is stored in the context object with an\r\nexpiration date/time matching what was returned in the permission so that\r\nthe validity of a token can be validated and reported on without making\r\na request to the Cosmos DB server.\r\n\r\n```powershell\r\n$collectionId = Get-CosmosDbCollectionResourcePath -Database MyDatabase -Id MyNewCollection\r\n$permission = Get-CosmosDbPermission -Context $cosmosDbContext -UserId dscottraynsford@contoso.com -Id r_mynewcollection -Resource $collectionId -TokenExpiry 7200\r\n# Future features planned to make creation of a resource context token from a permission easier\r\n$tokenParams = @{\r\n    Resource    = $collectionId\r\n    TimeStamp   = $permission[0].Timestamp\r\n    TokenExpiry = 7200\r\n    Token       = (ConvertTo-SecureString -String $permission[0].Token -AsPlainText -Force)\r\n}\r\n$contextToken = New-CosmosDbContextToken @tokenParams\r\n$resourceParams = @{\r\n    Account     = $cosmosDBContext.Account\r\n    Database    = MyDatabase\r\n    Token       = $contextToken\r\n}\r\n$resourceContext = New-CosmosDbContext @resourceParams\r\nGet-CosmosDbCollection -Context $resourceContext -Id MyNewCollection\r\n```\r\n\r\n### Working with Triggers\r\n\r\nGet a list of triggers for a collection in the database:\r\n\r\n```powershell\r\nGet-CosmosDbTrigger -Context $cosmosDbContext -CollectionId MyNewCollection\r\n```\r\n\r\nCreate a trigger for a collection in the database that executes after all operations:\r\n\r\n```powershell\r\n$body = @'\r\nfunction updateMetadata() {\r\n    var context = getContext();\r\n    var collection = context.getCollection();\r\n    var response = context.getResponse();\r\n    var createdDocument = response.getBody();\r\n\r\n    // query for metadata document\r\n    var filterQuery = 'SELECT * FROM root r WHERE r.id = \"_metadata\"';\r\n    var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback);\r\n    if(!accept) throw \"Unable to update metadata, abort\";\r\n\r\n    function updateMetadataCallback(err, documents, responseOptions) {\r\n        if(err) throw new Error(\"Error\" + err.message);\r\n\r\n        if(documents.length != 1) throw 'Unable to find metadata document';\r\n        var metadataDocument = documents[0];\r\n\r\n        // update metadata\r\n        metadataDocument.createdDocuments += 1;\r\n        metadataDocument.createdNames += \" \" + createdDocument.id;\r\n\r\n        var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) {\r\n            if(err) throw \"Unable to update metadata, abort\";\r\n        });\r\n\r\n        if(!accept) throw \"Unable to update metadata, abort\";\r\n        return;\r\n    }\r\n}\r\n'@\r\nNew-CosmosDbTrigger -Context $cosmosDbContext -CollectionId MyNewCollection -Id MyTrigger -TriggerBody $body -TriggerOperation All -TriggerType Post\r\n```\r\n\r\nUpdate an existing trigger for a collection in the database to execute before\r\nall operations:\r\n\r\n```powershell\r\n$body = @'\r\nfunction updateMetadata() {\r\n    var context = getContext();\r\n    var collection = context.getCollection();\r\n    var response = context.getResponse();\r\n    var createdDocument = response.getBody();\r\n\r\n    // query for metadata document\r\n    var filterQuery = 'SELECT * FROM root r WHERE r.id = \"_metadata\"';\r\n    var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery, updateMetadataCallback);\r\n    if(!accept) throw \"Unable to update metadata, abort\";\r\n\r\n    function updateMetadataCallback(err, documents, responseOptions) {\r\n        if(err) throw new Error(\"Error\" + err.message);\r\n\r\n        if(documents.length != 1) throw 'Unable to find metadata document';\r\n        var metadataDocument = documents[0];\r\n\r\n        // update metadata\r\n        metadataDocument.createdDocuments += 1;\r\n        metadataDocument.createdNames += \" \" + createdDocument.id;\r\n\r\n        var accept = collection.replaceDocument(metadataDocument._self, metadataDocument, function(err, docReplaced) {\r\n            if(err) throw \"Unable to update metadata, abort\";\r\n        });\r\n\r\n        if(!accept) throw \"Unable to update metadata, abort\";\r\n        return;\r\n    }\r\n}\r\n'@\r\nSet-CosmosDbTrigger -Context $cosmosDbContext -CollectionId MyNewCollection -Id MyTrigger -Body $body -TriggerOperation All -TriggerType Pre\r\n```\r\n\r\nRemove a trigger for a collection from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbTrigger -Context $cosmosDbContext -CollectionId MyNewCollection -Id MyTrigger\r\n```\r\n\r\n### Working with Stored Procedures\r\n\r\nGet a list of stored procedures for a collection in the database:\r\n\r\n```powershell\r\nGet-CosmosDbStoredProcedure -Context $cosmosDbContext -CollectionId MyNewCollection\r\n```\r\n\r\nCreate a stored procedure for a collection in the database:\r\n\r\n```powershell\r\n$body = @'\r\nfunction () {\r\n    var context = getContext();\r\n    var response = context.getResponse();\r\n\r\n    response.setBody(\"Hello, World\");\r\n}\r\n'@\r\nNew-CosmosDbStoredProcedure -Context $cosmosDbContext -CollectionId MyNewCollection -Id spHelloWorld -StoredProcedureBody $body\r\n```\r\n\r\nUpdate an existing stored procedure for a collection in the database:\r\n\r\n```powershell\r\n$body = @'\r\nfunction (personToGreet) {\r\n    var context = getContext();\r\n    var response = context.getResponse();\r\n\r\n    response.setBody(\"Hello, \" + personToGreet);\r\n}\r\n'@\r\nSet-CosmosDbStoredProcedure -Context $cosmosDbContext -CollectionId MyNewCollection -Id spHelloWorld -StoredProcedureBody $body\r\n```\r\n\r\nExecute a stored procedure for a collection from the database:\r\n\r\n```powershell\r\nInvoke-CosmosDbStoredProcedure -Context $cosmosDbContext -CollectionId MyNewCollection -Id spHelloWorld -StoredProcedureParameters @('PowerShell')\r\n```\r\n\r\nRemove a stored procedure for a collection from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbStoredProcedure -Context $cosmosDbContext -CollectionId MyNewCollection -Id spHelloWorld\r\n```\r\n\r\n### Working with User Defined Functions\r\n\r\nGet a list of user defined functions for a collection in the database:\r\n\r\n```powershell\r\nGet-CosmosDbUserDefinedFunction -Context $cosmosDbContext -CollectionId MyNewCollection\r\n```\r\n\r\nCreate a user defined function for a collection in the database:\r\n\r\n```powershell\r\n$body = @'\r\nfunction tax(income) {\r\n    if(income == undefined) throw 'no input';\r\n    if (income \u003c 1000)\r\n        return income * 0.1;\r\n    else if (income \u003c 10000)\r\n        return income * 0.2;\r\n    else\r\n        return income * 0.4;\r\n}\r\n'@\r\nNew-CosmosDbUserDefinedFunction -Context $cosmosDbContext -CollectionId MyNewCollection -Id udfTax -UserDefinedFunctionBody $body\r\n```\r\n\r\nUpdate an existing user defined function for a collection in the database:\r\n\r\n```powershell\r\n$body = @'\r\nfunction tax(income) {\r\n    if(income == undefined) throw 'no input';\r\n    if (income \u003c 1000)\r\n        return income * 0.2;\r\n    else if (income \u003c 10000)\r\n        return income * 0.3;\r\n    else\r\n        return income * 0.4;\r\n}\r\n'@\r\nSet-CosmosDbUserDefinedFunction -Context $cosmosDbContext -CollectionId MyNewCollection -Id udfTax -Body $body\r\n```\r\n\r\nRemove a user defined function for a collection from the database:\r\n\r\n```powershell\r\nRemove-CosmosDbUserDefinedFunction -Context $cosmosDbContext -CollectionId MyNewCollection -Id udfTax\r\n```\r\n\r\n### How to Handle Exceeding Provisioned Throughput\r\n\r\nWhen using Azure Cosmos DB it is quite common to exceed the throughput\r\nthat has been provisioned against a collection (or across multiple collections).\r\nSee [this page](https://docs.microsoft.com/azure/cosmos-db/request-units)\r\nfor more information on request units and throughput provisioning.\r\n\r\nWhen this happens requests will return a `Too Many Request` (error code 429).\r\nUsually just waiting a small amount of time and trying again will result in the\r\nrequest succeeding. However, the Cosmos DB PowerShell module provides a mechanism\r\nfor configuring an automatic back-off and retry policy.\r\n\r\nThis is configured within the Context object that is usually passed to each\r\nCosmos DB module function.\r\n\r\nTo configure a Back-off Policy, use the `New-CosmosDbBackoffPolicy` function:\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 5\r\n$cosmosDbContext = New-CosmosDbContext -Account MyAzureCosmosDB -Database MyDatabase -Key $primaryKey -BackoffPolicy $backoffPolicy\r\n```\r\n\r\nThis will cause any functions that use the Context to automatically retry up to\r\n5 times if a 429 response code is returned. Any other type of response code will\r\nthrow an exception. The number of milliseconds to delay before retrying will be\r\ndetermined automatically by using the `x-ms-retry-after-ms` header returned by\r\nCosmos DB.\r\n\r\nAdditional Back-off Policy options can be set to override or extend the value\r\nreturned in the `x-ms-retry-after-ms` header.\r\n\r\n**Note: if the delay calculated by the policy is less than the value returned in\r\nthe `x-ms-retry-after-ms` header, then the `x-ms-retry-after-ms` value will always\r\nbe used.**\r\n\r\nThe available Back-off Methods are:\r\n\r\n- Default\r\n- Additive\r\n- Linear\r\n- Exponential\r\n- Random\r\n\r\nThe following show examples of alternative policy back-off types that can\r\nimplemented:\r\n\r\n#### Default\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 10 -Method Default -Delay 100\r\n```\r\n\r\nThe delay of 100ms will always be used unless it is less than `x-ms-retry-after-ms`.\r\nThe delay can be set to 0 and will cause the  `x-ms-retry-after-ms` to always be\r\nused. It is the default Back-off Policy behavior.\r\n\r\n#### Additive\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 10 -Method Additive -Delay 1000\r\n```\r\n\r\nThis will create a policy that will retry 10 times with a delay equaling the\r\nvalue of the returned `x-ms-retry-after-ms` header plus 1000ms.\r\n\r\n#### Linear\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 3 -Method Linear -Delay 500\r\n```\r\n\r\nThis will create a policy that will wait for 500ms on the first retry, 1000ms on\r\nthe second retry, 1500ms on final retry.\r\n\r\n#### Exponential\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 4 -Method Exponential -Delay 1000\r\n```\r\n\r\nThis will create a policy that will wait for 1000ms on the first retry, 4000ms on\r\nthe second retry, 9000ms on the 3rd retry and 16000ms on the final retry.\r\n\r\n#### Random\r\n\r\n```powershell\r\n$backoffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 3 -Method Random -Delay 1000\r\n```\r\n\r\nA policy that adds or subtracts up to 50% of the delay period to the base delay\r\neach time can also be applied. For example, the first delay might be 850ms, with\r\nthe second delay being 1424ms and final delay being 983ms.\r\n\r\n## Compatibility and Testing\r\n\r\nThis PowerShell module is automatically tested and validated to run\r\non the following systems:\r\n\r\n- Windows Server (using Windows PowerShell 5.1):\r\n  - Windows Server 2019: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Windows Server 2022: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Windows Server 2025: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n- Windows Server (using Windows PowerShell 7.x):\r\n  - Windows Server 2019: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Windows Server 2022: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Windows Server 2025: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n- Linux (using PowerShell 7.x):\r\n  - Ubuntu 20.04: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Ubuntu 22.04: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - Ubuntu 24.04: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n- macOS (using PowerShell 7.x):\r\n  - macOS 13: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - macOS 14: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n  - macOS 15: Using [Azure Pipelines](https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4).\r\n\r\n\u003e This module is no longer tested on PowerShell Core 6.x as PowerShell 7.x\r\n\u003e should be used. It should still work, but will no longer be verified. Issues with\r\n\u003e this module that only exist on PowerShell Core 6.x but not PowerShell 7.x will\r\n\u003e not be fixed.\r\n\r\nThis module should function correctly on other systems and configurations\r\nbut is not automatically tested with them in every change.\r\n\r\n## Contributing\r\n\r\nIf you wish to contribute to this project, please read the [Contributing.md](/.github/CONTRIBUTING.md)\r\ndocument first. We would be very grateful of any contributions.\r\n\r\n## Cmdlets\r\n\r\nA list of Cmdlets in the _CosmosDB PowerShell module_ can be found by running the\r\nfollowing PowerShell commands:\r\n\r\n```PowerShell\r\nImport-Module -Name CosmosDB\r\nGet-Command -Module CosmosDB\r\n```\r\n\r\nHelp on individual Cmdlets can be found in the built-in Cmdlet help:\r\n\r\n```PowerShell\r\nGet-Help -Name Get-CosmosDBUser\r\n```\r\n\r\nThe details of the cmdlets contained in this module can also be\r\nfound in the [wiki](https://github.com/PlagueHO/CosmosDB/wiki).\r\n\r\n## Change Log\r\n\r\nFor a list of changes to versions, see the [CHANGELOG.md](CHANGELOG.md) file.\r\n\r\n## Links\r\n\r\n- [GitHub Repository](https://github.com/PlagueHO/CosmosDB/)\r\n- [Blog](https://dscottraynsford.wordpress.com/)\r\n\r\n[ap-image-main]: https://dev.azure.com/dscottraynsford/GitHub/_apis/build/status/PlagueHO.CosmosDB.main?branchName=main\r\n[ap-site-main]: https://dev.azure.com/dscottraynsford/GitHub/_build?definitionId=4\u0026_a=summary\r\n[ts-image-main]: https://img.shields.io/azure-devops/tests/dscottraynsford/GitHub/4/main\r\n[ts-site-main]: https://dev.azure.com/dscottraynsford/GitHub/_build/latest?definitionId=4\u0026branchName=main\r\n[cq-image-main]: https://api.codacy.com/project/badge/Grade/1ee50b5eb15b47c188b3bdf7a5f8ee1d\r\n[cq-site-main]: https://www.codacy.com/app/PlagueHO/CosmosDB?utm_source=github.com\u0026amp;utm_medium=referral\u0026amp;utm_content=PlagueHO/CosmosDB\u0026amp;utm_campaign=Badge_Grade\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPlagueHO%2FCosmosDB","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FPlagueHO%2FCosmosDB","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPlagueHO%2FCosmosDB/lists"}