Search code examples
powershellazureazure-powershellazure-queues

Azure PowerShell - How to Create Queue If Not Exists


I am using Azure PowerShell to create and add entries to an Azure queue, following example here: MSDN: Using Azure PowerShell with Azure Storage - How to manage Azure queues .

Here is my PowerShell script:

$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)

This works fine the first time I run it.

Second time, I get this:

New-AzureStorageQueue : Queue 'myqueue' already exists. At line:1 char:12 + $myQueue = New-AzureStorageQueue –Name 'myqueue' -Context $storeAuthContext + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (:) [New-AzureStorageQueue], ResourceAlreadyExistException + FullyQualifiedErrorId : ResourceAlreadyExistException,Microsoft.WindowsAzure.Commands.Storage.Queue.NewAzureStorageQueueCommand

In .NET Azure Storage API there is cloudqueue.createifnotexists (MSDN), but I cannot find the equivalent in Azure PowerShell.

What is the best way in PowerShell to create Azure storage queue if it does not already exist, otherwise get reference to the existing queue?


Solution

  • Afaik there is no CreateIfNotExist flag through the PowerShell module.

    You can easily do the following to achieve the same:

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

    If you want to surpress errors and always try to create it (regardless if it exists or not); you should be able to use the -ErrorAction SilentlyContinue when creating the queue.

    I would recommend the first approach though as it's a better practice.