Azure PowerShell - как создать очередь, если не существует

Я использую Azure PowerShell для создания и добавления записей в очередь Azure, следующий пример здесь: MSDN: Использование Azure PowerShell с хранилищем Azure - Как управлять очередями Azure.

Вот мой сценарий PowerShell:

$storeAuthContext = New-AzureStorageContext -StorageAccountName '[my storage account name]' -StorageAccountKey '[my storage account key'
$myQueue = New-AzureStorageQueue –Name 'myqueue' -Context $storeAuthContext
$queueMessage = New-Object -TypeName Microsoft.WindowsAzure.Storage.Queue.CloudQueueMessage -ArgumentList 'Hello'
$myQueue.CloudQueue.AddMessage($queueMessage)

Это отлично работает при первом запуске.

Второй раз получаю вот что:

New-AzureStorageQueue: очередь myqueue уже существует. В строке: 1 символ: 12 + $ myQueue = New-AzureStorageQueue –Name 'myqueue' -Context $ storeAuthContext + ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: ResourceExists: (:) [New-AzureStorageQueue ], ResourceAlreadyExistException + FullyQualifiedErrorId: ResourceAlreadyExistException, Microsoft.WindowsAzure.Commands.Storage.Queue.NewAzureStorageQueueCommand

В .NET Azure Storage API есть cloudqueue.createifnotexists (MSDN), но я не могу найти аналог в Azure PowerShell.

Как лучше всего в PowerShell создать очередь хранилища Azure, если она еще не существует, иначе получить ссылку на существующую очередь?


person Edward    schedule 26.02.2016    source источник


Ответы (2)


Afaik нет флага CreateIfNotExist через модуль PowerShell.

Вы можете легко сделать следующее, чтобы добиться того же:

$queue = Get-AzureStorageQueue -name 'myName' -Context $storeAuthContext
if(-not $queue){ 
    # your code to create the queue
}

Если вы хотите скрыть ошибки и всегда пытаться их создавать (независимо от того, есть они или нет); вы должны иметь возможность использовать -ErrorAction SilentlyContinue при создании очереди.

Я бы порекомендовал первый подход, так как это лучшая практика.

person Harald F.    schedule 26.02.2016
comment
Похоже, что New-AzureStorageQueue действительно делает это под капотом. Если вы посмотрите на код в GitHub, когда CmdLet вызывается, он выполняет CreateIfNotExists при вызове. (github .com / Azure / azure-powershell / blob / dev / src / Common / Storage /). Обратите внимание, что это может выглядеть немного странно в вашем коде сценария, если всегда использовать New-AzureStorageQueue, а код, указанный CmdrTchort, более читабельный. Теоретически вы получите очередь гораздо чаще, чем ее не будет, и ее нужно будет создать. - person MikeWo; 26.02.2016
comment
@MikeWo - Вы описываете, как я ожидал, что это сработает, но я получил исключение ResourceAlreadyExistsException, когда попробовал, отсюда и мой вопрос. Однако ответ, отправленный CmdrTchort, работает. - person Edward; 26.02.2016
comment
@Edward Ах, да, потому что, если бы я посмотрел на этот код еще немного, я бы увидел, что он явно выбрасывает ResourceAlreadyExistException. DOH! - person MikeWo; 26.02.2016

По состоянию на 2017.03.14 принятый ответ не работал в функции Powershell Azure, Get-AzureStorageQueue выдает исключение, если указанная очередь не существует.

Пример:

Вот код

$storageAccountName = $env:AzureStorageAccountName
Write-Output ("storageAccountName: {0}" -f $storageAccountName)
$storageAccountKey = $env:AzureStorageAccountKey
Write-Output ("storageAccountKey: {0}" -f $storageAccountKey)
$storageQueueName = $env:AzureStorageQueueName
Write-Output ("storageAccountKey: {0}" -f $storageAccountKey)

Write-Output "Creating storage context"
$azureStorageContext = New-AzureStorageContext $storageAccountName -    StorageAccountKey $storageAccountKey

Write-Output "Retrieving queue"
$azureStorageQueue = Get-AzureStorageQueue -Name $storageQueueName –Context $azureStorageContext

Вот журнал

2017-03-15T04:16:57.021 Get-AzureStorageQueue : Can not find queue 'my-queue-name'.
at run.ps1: line 21
+ Get-AzureStorageQueue
+ _____________________
    + CategoryInfo          : ObjectNotFound: (:) [Get-AzureStorageQueue], ResourceNotFoundException
    + FullyQualifiedErrorId : ResourceNotFoundException,Microsoft.WindowsAzure.Commands.Storage.Queue.GetAzureStorageQueueCommand
2017-03-15T04:16:57.021 Function completed (Failure, Id=58f35998-ebe0-4820-ac88-7d6ca42833df)

Разрешение

Мне приходилось фильтровать результаты и создавать очередь только в том случае, если ее не было. вот как это решить:

Write-Output "Retrieving queue"
# Get-AzureStorageQueue returns an exception if the queue does not exists when passing -Name, so instead
# we need to get them all, filter by Name, and if null, create it
$azureStorageQueue = Get-AzureStorageQueue –Context $azureStorageContext | Where-Object {$_.Name -eq $storageQueueName}
if ($azureStorageQueue -eq $null)
{
    Write-Output "Queue does not exist, creating it"
    $azureStorageQueue = New-AzureStorageQueue -Name $storageQueueName -Context $azureStorageContext
}
person Rick Glos    schedule 15.03.2017
comment
Спасибо, фильтрация была той частью, которую мне не хватало - person Thomas; 24.11.2017
comment
В качестве альтернативы просто поместите Get-AzStorageQueue в try / catch и в вызове catch New-AzStorageQueue - person Simon; 12.11.2020