Tuesday, October 24, 2023

PowerShell script to export data Cosmos DB to a CSV file

 # Set your Cosmos DB account and database details

$resourceGroupName = "<<Resource Group Name>>"

$accountName = "<<Azure Cosmos DB Account Name>>"

$databaseName = "<<Database Name>>"

$containerName = "<<container Name>>"

# Set the output CSV file path

$outputCsvFilePath = "<<Location>>\export.csv"

# Query to retrieve data from Cosmos DB

$query = "SELECT * FROM c"

# Authenticate to your Azure account (if not already authenticated)

# Connect-AzAccount

# Get the Cosmos DB container

$container = Get-AzCosmosDBSqlContainer -ResourceGroupName $resourceGroupName -AccountName $accountName -DatabaseName $databaseName -Name $containerName

# Execute the query and export the results to a CSV file

$queryResult = $container | Invoke-AzCosmosDBSqlQuery -Query $query

# Convert the result to a PowerShell object

$cosmosData = $queryResult | ConvertFrom-Json

# Export the data to a CSV file

$cosmosData | Export-Csv -Path $outputCsvFilePath -NoTypeInformation

Write-Host "Data exported to $outputCsvFilePath"