Automate Cosmos DB Integration Tasks from PowerShell
The CData ADO.NET Provider for Cosmos DB is a standard ADO.NET Provider that make it easy to accomplish data cleansing, normalization, backup, and other integration tasks by enabling real-time and bidirectional access to Cosmos DB.
ADO.NET Provider
The ADO.NET Provider provides a SQL interface for Cosmos DB; this tutorial shows how to use the Provider to create, retrieve, update, and delete Cosmos DB data.
Once you have acquired the necessary connection properties, accessing Cosmos DB data in PowerShell can be enabled in three steps.
To obtain the connection string needed to connect to a Cosmos DB account using the SQL API, log in to the Azure Portal, select Azure Cosmos DB, and select your account. In the Settings section, click Connection String and set the following values:
- AccountEndpoint: The Cosmos DB account URL from the Keys blade of the Cosmos DB account
- AccountKey: In the Azure portal, navigate to the Cosmos DB service and select your Azure Cosmos DB account. From the resource menu, go to the Keys page. Find the PRIMARY KEY value and set AccountKey to this value.
-
Load the provider's assembly:
[Reflection.Assembly]::LoadFile("C:\Program Files\CData\CData ADO.NET Provider for Cosmos DB\lib\System.Data.CData.CosmosDB.dll") -
Connect to Cosmos DB:
$conn= New-Object System.Data.CData.CosmosDB.CosmosDBConnection("AccountEndpoint=myAccountEndpoint;AccountKey=myAccountKey;") $conn.Open() -
Instantiate the CosmosDBDataAdapter, execute an SQL query, and output the results:
$sql="SELECT City, CompanyName from Customers" $da= New-Object System.Data.CData.CosmosDB.CosmosDBDataAdapter($sql, $conn) $dt= New-Object System.Data.DataTable $da.Fill($dt) $dt.Rows | foreach { Write-Host $_.city $_.companyname }
Update Cosmos DB Data
$cmd = New-Object System.Data.CData.CosmosDB.CosmosDBCommand("UPDATE Customers SET Name='Morris Park Bake Shop' WHERE id = @myid", $conn)
$cmd.Parameters.Add((New-Object System.Data.CData.CosmosDB.CosmosDBParameter("@myid","10456255-0015501366")))
$cmd.ExecuteNonQuery()
Insert Cosmos DB Data
$cmd = New-Object System.Data.CData.CosmosDB.CosmosDBCommand("INSERT INTO Customers (Name) VALUES (@myName)", $conn)
$cmd.Parameters.Add((New-Object System.Data.CData.CosmosDB.CosmosDBParameter("@myName","Morris Park Bake Shop")))
$cmd.ExecuteNonQuery()
Delete Cosmos DB Data
$cmd = New-Object System.Data.CData.CosmosDB.CosmosDBCommand("DELETE FROM Customers WHERE id=@myid", $conn)
$cmd.Parameters.Add((New-Object System.Data.CData.CosmosDB.CosmosDBParameter("@myid","001d000000YBRseAAH")))
$cmd.ExecuteNonQuery()
CodeProject