我很高兴找到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
}
}
更新
如下所示,您必须使用Get-AzureStorageTable来检查表是否已经存在。
$tablename = "test"
$table = Get-AzureStorageTable $tablename -Context $context -ErrorAction Ignore
if ($table -eq $null)
{
New-AzureStorageTable $tablename -Context $context
}
答案 0 :(得分:5)
这是使用存储客户端库(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
}
}
<强>更新强>
我刚刚尝试了上面的代码,它完全正常 if the table does not exist in storage
。如果我尝试为存储中已存在的表运行此脚本,我能够重现您正在获得的错误。我认为这就是发生的事情:当你调用New-AzureStorageTable
创建一个表时,如果表已经存在,那么它会抛出一个错误并为null
变量返回$table
值,然后当您尝试使用此InsertRow
值null
变量执行$table
函数时,Execute
函数会出错。理想情况下,New-AzureStorageTable
如果表已经存在,则不应该出错。