## Wednesday, November 20, 2013

### How to insert entities into Azure Table Storage using Powershell.

In order to insert entities into Azure Table storage while executing powershell scripts, for example IAAS scripts where you want to log any kind of deployment information, this is one of the approach that can be followed. Ofcourse the code is not optimized, but you get the idea of how to go about.

In the code below, at runtime, we define the entity that you want to log. Remember, as per the table storage requirements, the PartitionKey and RowKey is mandatory and rest of the fields can be anything you want.

Advantage of creating an entity at runtime is that you dont have to deploy any C# dll along with powershell scripts which would make things simple.

Add-Type -Path "C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\v2.2\ref\Microsoft.WindowsAzure.Storage.dll"

$refs = @( "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Data.Services.Client.dll")$code = @"

using System;
using System.Data.Services.Common;

[DataServiceEntity]
public class LogEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Client { get; set; }
public string Criteria { get; set; }
public string DeploymentID { get; set; }
public string MachineName { get; set; }

}

"@

Add-Type -ReferencedAssemblies $refs -TypeDefinition$code

$accountName = "youraccountname"$accountKey = "youraccountkey"

$credentials = new-object Microsoft.WindowsAzure.Storage.Auth.StorageCredentials($accountName, $accountKey);$uri = New-Object System.Uri("http://yourstorageaccount.table.core.windows.net/");

$tableClient = New-Object Microsoft.WindowsAzure.Storage.Table.CloudTableClient($uri,$credentials);$table = $tableClient.GetTableReference("log"); # here log is the table name you want$table.CreateIfNotExists();
$entity = New-Object LogEntity;$entity.PartitionKey = "p4";
$entity.RowKey="r4";$entity.Client="C1";
$entity.Criteria = "crit";$entity.DeploymentID = "D1";
$entity.MachineName = "M1";$context = $tableClient.GetTableServiceContext();$context.AddObject("log", $entity);$context.SaveChanges();