如何使用PowerShell在Azure存储表中插入行

Sim*_*raa 2 azure azure-table-storage powershell-3.0

我很高兴找到New-AzureStorageTable cmdlet,但我还没想出如何在表中插入新行.

我在互联网上找到了以下代码,但CloudTable.Execute似乎失败了.

它需要三个参数,如http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.execute(v=azure.10).aspx中所述,但我无法弄清楚如何调用方法.

任何想法都表示赞赏!

function InsertRow($table, [String]$partitionKey, [String]$rowKey, [int]$intValue)
{
  $entity = New-Object "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity" $partitionKey, $rowKey
  $entity.Properties.Add("IntValue", $intValue)
  $result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::Insert($entity))
}

$StorageAccountName = "MyAccountName"
$StorageAccountKey = "MyAccountKey"

$context = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$table = New-AzureStorageTable test -Context $context

for ($p = 1; $p -le 10; $p++)
{
  for ($r = 1; $r -le 10; $r++)
  {
    InsertRow $table "P$p" "R$r" $r
  }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

如下所示,您必须使用Get-AzureStorageTable来检查表是否已经存在.

$tablename = "test"
$table = Get-AzureStorageTable $tablename -Context $context -ErrorAction Ignore
if ($table -eq $null)
{
    New-AzureStorageTable $tablename -Context $context
}
Run Code Online (Sandbox Code Playgroud)

Gau*_*tri 5

这是使用Storage Client Library(Microsoft.WindowsAzure.Storage.dll)的替代实现.

#Insert row ... here $table is an object of type CloudTable
function InsertRow($table, [String]$partitionKey, [String]$rowKey, [int]$intValue)
{
  $entity = New-Object "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity" $partitionKey, $rowKey
  $entity.Properties.Add("IntValue", $intValue)
  $result = $table.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::Insert($entity))
}


$StorageAccountName = "accountname"
$StorageAccountKey = "accountkey"
$tableName = "MyTable3"

#Create instance of storage credentials object using account name/key
$accountCredentials = New-Object "Microsoft.WindowsAzure.Storage.Auth.StorageCredentials" $StorageAccountName, $StorageAccountKey

#Create instance of CloudStorageAccount object
$storageAccount = New-Object "Microsoft.WindowsAzure.Storage.CloudStorageAccount" $accountCredentials, $true

#Create table client
$tableClient = $storageAccount.CreateCloudTableClient()

#Get a reference to CloudTable object
$table = $tableClient.GetTableReference($tableName)

#Try to create table if it does not exist
$table.CreateIfNotExists()

for ($p = 1; $p -le 10; $p++)
{
  for ($r = 1; $r -le 10; $r++)
  {
    InsertRow $table "P$p" "R$r" $r
  }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

我只是尝试了上面的代码,它完全正常if the table does not exist in storage.如果我尝试为存储中已存在的表运行此脚本,我能够重现您获得的错误.我认为这是正在发生的事情:当你调用New-AzureStorageTable创建一个表时,如果表已经存在,那么它会抛出一个错误并返回一个变量null$table,然后当你尝试InsertRow使用这个null$table变量执行函数时,你会得到Execute函数错误.New-AzureStorageTable如果表已经存在,理想情况下不应该出错.