Skip to content
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
b8776d5
Add New-CosmosDbTransactionalBatch command
ArmaanMcleod Nov 15, 2025
9245c55
Add output type to command
ArmaanMcleod Nov 15, 2025
fac1112
Add docs
ArmaanMcleod Nov 15, 2025
0115b60
Set type on batch operations
ArmaanMcleod Nov 15, 2025
f69d7a6
Add unit tests
ArmaanMcleod Nov 15, 2025
8034788
Add integration tests
ArmaanMcleod Nov 15, 2025
0c9d117
Updated change log
ArmaanMcleod Nov 15, 2025
f4575a4
Add output type and parameter type to Set-CosmosDbTransactionalBatchO…
ArmaanMcleod Nov 15, 2025
8d55068
Fix formatting for Project name base name in test
ArmaanMcleod Nov 15, 2025
c2eb2e7
Add format XML
ArmaanMcleod Nov 15, 2025
e17fd11
Add supports should process for transactional batch
ArmaanMcleod Nov 15, 2025
dbccd92
Remove unnecessary integration tests
ArmaanMcleod Nov 15, 2025
c65843e
Test JSON contents in ReturnJson test
ArmaanMcleod Nov 15, 2025
ac445e0
move should process to beginning of cmdlet
ArmaanMcleod Nov 15, 2025
b670c35
Add should process tests and wrapped around web request block
ArmaanMcleod Nov 15, 2025
75e0e06
Add Copilot suggestions
ArmaanMcleod Nov 16, 2025
0c6e117
Update source/Public/transactionalbatch/New-CosmosDbTransactionalBatc…
ArmaanMcleod Nov 16, 2025
0dd03b0
Fix typo with headers
ArmaanMcleod Nov 16, 2025
a553eb3
Merge branch 'main' into transactional-batch
ArmaanMcleod Nov 16, 2025
0b14be8
Use booleans for headers in mocks instead of strings
ArmaanMcleod Nov 16, 2025
dc8f0db
Add more unit tests
ArmaanMcleod Nov 16, 2025
7593626
Apply suggestions from code review
ArmaanMcleod Nov 16, 2025
a04fb27
Replace IsAtomic boolean flag with NoAtomic switch
ArmaanMcleod Nov 16, 2025
b7b2bbe
Remove related links from docs
ArmaanMcleod Nov 16, 2025
e287b7c
Simplified formats and types to be more readable with important prope…
ArmaanMcleod Nov 16, 2025
3459ee0
Add SupportsShouldProcess to Set-CosmosDbTransactionalBatchOperationType
ArmaanMcleod Nov 20, 2025
ab1c15d
Fix markdown linter errors
ArmaanMcleod Nov 20, 2025
af580a2
Fix markdown line length error in CHANGELOG
ArmaanMcleod Nov 20, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Added `New-CosmosDbTransactionalBatch` function to create a new transactional batch
for performing multiple operations on items in a Cosmos DB container.

## [6.1.0] - 2025-06-08

### Fixed
Expand Down
194 changes: 194 additions & 0 deletions docs/New-CosmosDbTransactionalBatch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
---
external help file: CosmosDB-help.xml
Module Name: CosmosDB
online version:
schema: 2.0.0
---

# New-CosmosDbTransactionalBatch

## SYNOPSIS

Execute a transactional batch operation against a collection in a Cosmos DB database.

## SYNTAX

```powershell
New-CosmosDbTransactionalBatch -Context <Context> -PartitionKey <String> -CollectionId <String>
-Documents <Object[]> [-OperationType <String>] [-IsAtomic <Boolean>] [-ReturnJson <switch>] [<CommonParameters>]
```

## DESCRIPTION

This cmdlet will execute a transactional batch operation against a collection in a Cosmos DB database. All operations in the batch will target documents within the same partition key. If IsAtomic is true (default), either all operations succeed or all operations are rolled back.

## EXAMPLES

### Example 1: Create multiple documents atomically

```powershell
PS C:\> $documents = @(
@{ id = 'doc1'; name = 'Alice'; customerId = 'test' },
@{ id = 'doc2'; name = 'Bob'; customerId = 'test' }
)
PS C:\> New-CosmosDbTransactionalBatch -Context $context -PartitionKey 'test' -CollectionId 'Customers' -Documents $documents -OperationType 'Create'
```

### Example 2: Upsert documents with atomic behavior disabled

```powershell
PS C:\> $documents = @(
@{ id = 'doc1'; name = 'Alice Updated'; customerId = 'test' },
@{ id = 'doc2'; name = 'Bob Updated'; customerId = 'test' }
)
PS C:\> New-CosmosDbTransactionalBatch -Context $context -PartitionKey 'test' -CollectionId 'Customers' -Documents $documents -OperationType 'Upsert' -IsAtomic $false
```

### Example 3: Return raw JSON response

```powershell
PS C:\> $result = New-CosmosDbTransactionalBatch -Context $context -PartitionKey 'test' -CollectionId 'Customers' -Documents $documents -ReturnJson
PS C:\> $result | ConvertFrom-Json
```

## PARAMETERS

### -Context

This is an object containing the context information of the Cosmos DB database that will be deleted. It should be created by `New-CosmosDbContext`.

```yaml
Type: Context
Parameter Sets: (All)
Aliases: Connection

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PartitionKey
This is the partition key value for all documents in the batch. All documents must belong to the same partition.
```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CollectionId
This is the Id of the collection to execute the batch operation against.
```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Documents
An array of documents to include in the batch operation. Each document will be processed using the specified OperationType.
```yaml
Type: Object[]
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -OperationType
The type of operation to perform on each document in the batch. Valid values are: Create, Upsert, Read, Replace, Delete.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Accepted values: Create, Upsert, Read, Replace, Delete

Required: False
Position: Named
Default value: Create
Accept pipeline input: False
Accept wildcard characters: False
```
### -IsAtomic
Determines whether the batch operation should be atomic. If true (default), either all operations succeed or all are rolled back. If false, individual operations can succeed or fail independently.
```yaml
Type: Boolean
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: True
Accept pipeline input: False
Accept wildcard characters: False
```
### -ReturnJson
Return the raw JSON response from Cosmos DB instead of parsed objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### None
## OUTPUTS
### System.Object[]
Returns an array of batch operation results, one for each document in the batch.
## NOTES
- All documents in a batch must belong to the same partition key
- Maximum of 100 operations per batch
- Each operation result includes statusCode, requestCharge, eTag, and resourceBody properties
- When IsAtomic is true, any operation failure will roll back the entire batch
## RELATED LINKS
[New-CosmosDbDocument](New-CosmosDbDocument.md)
[New-CosmosDbContext](New-CosmosDbContext.md)
4 changes: 3 additions & 1 deletion source/CosmosDB.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
'formats\triggers.formats.ps1xml',
'formats\userdefinedfunctions.formats.ps1xml',
'formats\users.formats.ps1xml'
'formats\transactionalbatch.formats.ps1xml'
)

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
Expand Down Expand Up @@ -97,7 +98,8 @@
'Set-CosmosDbAccount', 'Set-CosmosDbAttachment',
'Set-CosmosDbCollection', 'Set-CosmosDbDocument', 'Set-CosmosDbOffer',
'Set-CosmosDbStoredProcedure', 'Set-CosmosDbTrigger',
'Set-CosmosDbUser', 'Set-CosmosDbUserDefinedFunction')
'Set-CosmosDbUser', 'Set-CosmosDbUserDefinedFunction',
'New-CosmosDbTransactionalBatch')

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function Set-CosmosDbTransactionalBatchOperationType
{
[CmdletBinding()]
[OutputType([System.Object[]])]
param
(
[Parameter(Mandatory = $true)]
[System.Object[]]
$BatchOperations
)

foreach ($item in $BatchOperations)
{
$item.PSObject.TypeNames.Insert(0, 'CosmosDB.TransactionalBatchOperation')
}

return $BatchOperations
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
function New-CosmosDbTransactionalBatch
{
[CmdletBinding(SupportsShouldProcess = $true)]
[OutputType([System.Object[]])]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[CosmosDb.Context]
$Context,

[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$PartitionKey,

[Parameter(Mandatory = $true)]
[ValidateScript({ Assert-CosmosDbCollectionIdValid -Id $_ -ArgumentName 'CollectionId' })]
[System.String]
$CollectionId,

[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Object[]]
$Documents,

[Parameter(Mandatory = $false)]
[ValidateSet('Create', 'Upsert', 'Read', 'Replace', 'Delete')]
[System.String]
$OperationType = 'Create',

[Parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[System.Boolean]
$IsAtomic = $true,

[Parameter()]
[System.Management.Automation.SwitchParameter]
$ReturnJson
)

$operationDescription = $LocalizedData.ShouldExecuteTransactionalBatch -f $Documents.Count, $OperationType.ToLower(), $CollectionId, $PartitionKey

if (-not $PSCmdlet.ShouldProcess('Azure', $operationDescription))
{
return
}

$operations = $Documents | ForEach-Object {
@{
operationType = $OperationType
resourceBody = $_
}
}

$batchBody = $operations | ConvertTo-Json -Depth 100 -Compress -AsArray

$resourcePath = 'colls/{0}/docs' -f $CollectionId

$headers = @{
'x-ms-cosmos-is-batch-request' = $IsAtomic
'x-ms-cosmos-batch-atomic' = $true
'x-ms-documentdb-partitionkey' = "[`"$PartitionKey`"]"
}

$result = Invoke-CosmosDbRequest `
-Context $Context `
-Method 'Post' `
-ResourceType 'docs' `
-ResourcePath $resourcePath `
-Body $batchBody `
-Headers $headers `
-ApiVersion '2018-12-31'

if ($ReturnJson.IsPresent)
{
return $result.Content
}

try
{
$batchOperations = $result.Content | ConvertFrom-Json
return (Set-CosmosDbTransactionalBatchOperationType -BatchOperations $batchOperations)
}
catch
{
New-CosmosDbInvalidOperationException -Message ($LocalizedData.ErrorConvertingDocumentJsonToObject)
}
}
1 change: 1 addition & 0 deletions source/en-US/CosmosDB.strings.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ ConvertFrom-StringData -StringData @'
ShouldUpdateAzureCosmosDBAccount = Update an Azure Cosmos DB account '{0}' in resource group '{1}'
ShouldRemoveAzureCosmosDBAccount = Remove the Azure Cosmos DB account '{0}' in resource group '{1}'
ShouldCreateAzureCosmosDBAccountMasterKey = Create a new Azure Cosmos DB account '{0}' '{2}' in resource group '{1}'
ShouldExecuteTransactionalBatch = Execute transactional batch with {0} {1} operation(s) on collection '{2}' with partition key '{3}'
AccountNameInvalid = The Account Name '{0}' is invalid. The name can contain only lowercase letters, numbers and the '-' character, and must be between 3 and 50 characters.
ResourceGroupNameInvalid = The Resource Group Name '{0}' is invalid. Resource group names only allow alphanumeric characters, periods, underscores, hyphens and parenthesis, cannot end in a period and must be 90 characters or less.
AttachmentIdInvalid = The Attachment Id '{0}' is invalid. An Attachment Id must not contain characters '\','/','#' or '?', end with a space or be longer than 255 characters.
Expand Down
Loading