如何在PowerShell中处理Azure存储TableOperation错误?

时间:2014-10-02 12:47:28

标签: powershell error-handling azure-storage

有一段时间,当我尝试在Azure表存储中插入数据时,我收到以下错误。

Exception calling "Execute" with "1" argument(s): "The remote server returned an error: (409) Conflict."

理论上,当我使用已经存在的分区键和行键插入数据时,可能会发生这种情况。

因为我使用刻度线(一个刻度是一千万分之一秒)对于分区键和行键我不认为应该是这种情况。示例如下。

但无论如何,我怎样才能阻止CloudTable.Execute上的例外?因为我已设置$ErrorActionPreference = "Stop",所以它将停止我的安装脚本。我认为我不能使用-ErrorAction Ignore

function Corax-Create-Table($tablename)
{
    $context = New-AzureStorageContext -StorageAccountName $g_storage_account_name -StorageAccountKey $g_storage_account_key
    $table = Get-AzureStorageTable $tablename -Context $context
    if ($table -eq $null)
    {
        New-AzureStorageTable $tablename -Context $context
    }
    return $table
}

function Corax-Storage-Insert-Message($table, [String]$partitionKey, [String]$rowKey, [String]$category, [String]$level, [String]$message)
{
    $entity = New-Object "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity" $partitionKey, $rowKey
    $entity.Properties.Add("Category", $category)
    $entity.Properties.Add("Level", $level)
    $entity.Properties.Add("Message", $message)
    $result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::Insert($entity))
}

$session = $(Get-Date).Ticks

$t = Corax-Create-Table('test')
Corax-Storage-Insert-Message $t $session $(Get-Date).Ticks "Database" "Progress" "Database table 1 is updated"
Corax-Storage-Insert-Message $t $session $(Get-Date).Ticks "Database" "Progress" "Database table 2 is updated"
Corax-Storage-Insert-Message $t $session $(Get-Date).Ticks "Database" "Progress" "Database table 3 is updated"
Corax-Storage-Insert-Message $t $session $(Get-Date).Ticks "Database" "Progress" "Database table 4 is updated"
Corax-Storage-Insert-Message $t $session $(Get-Date).Ticks "Database" "Progress" "Database table 5 is updated"

1 个答案:

答案 0 :(得分:0)

您尝试过try/catch吗?

function Corax-Storage-Insert-Message($table, [String]$partitionKey, [String]$rowKey, [String]$category, [String]$level, [String]$message)
{
    $ErrorActionPreference = "Stop"
    try{
        $entity = New-Object "Microsoft.WindowsAzure.Storage.Table.DynamicTableEntity" $partitionKey, $rowKey
        $entity.Properties.Add("Category", $category)
        $entity.Properties.Add("Level", $level)
        $entity.Properties.Add("Message", $message)
        $result = $table.CloudTable.Execute([Microsoft.WindowsAzure.Storage.Table.TableOperation]::Insert($entity))
    }
    catch{      
        ## error handling code      
    }
}

在捕获中,您可以使用递增的键记录错误或再次执行调用:

Corax-Storage-Insert-Message $table $partitionKey [String]([int]$rowKey + 1) $category $level $message