Azure: How to check storage account exists in Azure with Get-AzureStorageAccount
Asked Answered
M

9

6

I am building a power shell script to automate the setup of a website environment in Azure. This web uses an account storage. I want to the script not to create the account storage if exists.

I thought that using Get-AzureStorageAccount this way may work but it does not:

Write-Verbose "[Start] creating $Name storage account $Location location"

$storageAcct = Get-AzureStorageAccount –StorageAccountName $Name
if (!$storageAcct)
{   
    $storageAcct = New-AzureStorageAccount -StorageAccountName $Name -Location $Location -Verbose
    if ($storageAcct)
    {
        Write-Verbose "[Finish] creating $Name storage account in $Location location"
    }
    else
    {
        throw "Failed to create a Windows Azure storage account. Failure in New-AzureStorage.ps1"
    }
}
else
{
    Write-Verbose "$Name storage account in $Location location already exists, skipping creation"
}

The issue is I don't know how to handle the return of Get-AzureStorageAccount.

Thank you very much in advance!

Mendie answered 23/6, 2014 at 11:5 Comment(2)
Could you elaborate? What do you mean by ".. don't know how to handle the return of Get-AzureStorageAccount.`? What is happening and what do you want to happen?Anode
If Get-AzureStorageAccount does not return an storage account with the name I provide then create the storage account, otherwise skip the step.Mendie
H
16

I would suggest using the Test-AzureName cmdlet to determine if it exists. So, something like this.

if (!(Test-AzureName -Storage $Name))
{  
    Write-Host "Creating Storage Account $Name"
    New-AzureStorageAccount -StorageAccountName $Name -Location $Location 
}

You can use Test-AzureName for other services too, such as Cloud Services, WebSites, and ServiceBus. It returns True if it exists, False otherwise.

Heelandtoe answered 23/6, 2014 at 15:15 Comment(0)
U
5
Get-AzureRmStorageAccountNameAvailability -Name "accountname"
Unwish answered 26/9, 2016 at 19:45 Comment(0)
A
3

Try this:

$Name = "myStorageAccount"
$Location = "myLocation"

Write-Host "[Start] creating $Name storage account $Location location"
try{
    Get-AzureStorageAccount –StorageAccountName $Name -ErrorAction Stop | Out-Null
    Write-Host "$Name storage account in $Location location already exists, skipping creation"
    }
catch{
    Write-Host "[Finish] creating $Name storage account in $Location location"
    New-AzureStorageAccount -StorageAccountName $Name -Location $Location -Verbose      
}
Anode answered 23/6, 2014 at 14:51 Comment(0)
L
2

With the current Az module for PowerShell Version 7, the Get-AzStorageAccountNameAvailability cmdlet might offer a more efficient solution as it was designed specifically for this task. Here is an example:

# ... declare variables and specify values ...

$checkNameAvail = (Get-AzStorageAccountNameAvailability -Name $storageAccountName) | `
Select-Object NameAvailable

if ($checkNameAvail.NameAvailable) 
{
  Write-Host 'Account name available! Please wait while your resource is being created'

  # Create account. Variables used in this example would have been declared earlier in the script.
  $storageAccount = (New-AzStorageAccount -ResourceGroupName $resourceGroupName `
    -AccountName $storageAccountName `
    -Location $location `
    -SkuName $skuType `
    -AllowBlobPublicAccess $false -EnableHttpsTrafficOnly $true)
# ... 
}
else 
{
  # This section of the script executes if the name is not available
  Write-Host "The name <$storageAccountName> is not available. Suggest a new globally unique name!"
}

The condition above will return False, and execute the else statement because the boolean value returned by the cmdlet is in [0] as shown in the PowerShell command-line test below. The availability information (boolean) can thus be stripped from the object returned by the cmdlet and (as in this example) used as a condition in the rest of the script.

PS C:\> Get-AzStorageAccountNameAvailability -Name testaccount1

NameAvailable        Reason Message
-------------        ------ -------
        False AlreadyExists The storage account named testaccount1 is already taken.
Lymphosarcoma answered 16/6, 2021 at 14:34 Comment(1)
In 2024, this is the correct answer: we should be using Az module for PowerShell Version 7Alexei
C
1

Test-AzureName didn't work with our build agents and we already had a try/catch in code so a second one would require building it out as a function. I opted for that standard get and check if null, use -ErrorAction Ignore to stop it throwing an exception

# Check for storage account and create if not found    
$StorageAccount = Get-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $StorageAccountRG -ErrorAction Ignore
if ($StorageAccount -eq $null)  
{    
    New-AzureRmStorageAccount -Location "West Europe" -Name $StorageAccountName -ResourceGroupName $StorageAccountRG -SkuName Standard_LRS -Kind Storage     
    $StorageAccount = Get-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $StorageAccountRG   
}
Consuelaconsuelo answered 28/7, 2016 at 16:3 Comment(0)
I
1

@Rick Rainey's solution works if you're logged in using Add-AzureAccount. However, Azure and powershell have a conflicting and confusing suite of login accounts (Windows Live versus AD) and login mechanisms (Classic: Add-AzureAccount; Resource manager: Login-AzureRmAccount). Some Azure powershell cmdlets require a specific login; further, some require a specific account type!

To clear through this thicket of complicated, undocumented, and confusing permission issues, we always use an AD account, logging in via Login-AzureRmAccount. We also use Azure resource manager (ARM) resources and cmdlets, following Microsoft's movement to ARM as its recommended and strategic approach. However, @RIck's solution is one which the ARM login doesn't work with. :-( So you need another approach, which is @Darren's (for storage). However, for a generic replacement for Test-AzureName I'd suggest Find-AzureRmResource. In the case of storage

$StorageObject = Find-AzureRmResource -ResourceType "Microsoft.Storage/storageAccounts" | Where-Object {$_.Name -eq $storageName}        
if  ( !$StorageObject ) {
    $storageLocation = (Get-AzureRmResourceGroup -ResourceGroupName $resourceGroup).Location
    $storageType = "Standard_LRS"
    New-AzureRmStorageAccount -ResourceGroupName $resourceGroup  -Name $storageName -Location $storageLocation -Type $storageType
}
Ibo answered 30/7, 2016 at 17:12 Comment(0)
C
1

You should use the latest Powershell module Az.

if ($(Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName) -eq $null)
{
    # does not exist
}
Contradiction answered 22/1, 2020 at 19:33 Comment(0)
B
0

Use the error variable

Get-AzStorageAccount -ResourceGroupName 'RG-QA-TEST' -Name 'staccountfor12334ff' -ErrorVariable ev1 -ErrorAction SilentlyContinue

if ($ev1) {
    Write-Host "-------------------------- Creating OEM Storage"
    //create storage account
}
Brasil answered 4/2, 2020 at 11:23 Comment(1)
Thanks for your answer. Please consider to put your code in a code environment next time :-)Krutz
S
0

I had this challenge when setting up Azure storage accounts for Static website hosting using Powershell in Octopus Deploy.

Here's how I fixed it:

Using the Az module for Azure Powershell I did the following:

# Define Variables
$RESOURCE_GROUP_NAME = my-resource-group
$LOCATION = northeurope
$STORAGE_ACCOUNT_NAME = myapplication
$SKU_NAME = Standard_GRS
$STORAGE_KIND = StorageV2

# Check Storage Account and Create if not Found
$STORAGE_ACCOUNT = Get-AzStorageAccount -ResourceGroupName $RESOURCE_GROUP_NAME -Name $STORAGE_ACCOUNT_NAME -ErrorAction Ignore

if ($STORAGE_ACCOUNT -eq $null)  {    
    Write-Host 'Creating storage account'
    New-AzStorageAccount -ResourceGroupName $RESOURCE_GROUP_NAME -AccountName $STORAGE_ACCOUNT_NAME -Location $LOCATION -SkuName $SKU_NAME -Kind $STORAGE_KIND
    Write-Host "$STORAGE_ACCOUNT_NAME storage account successfully created"
}
else {
    Write-Host "$STORAGE_ACCOUNT_NAME storage account already exists"
}

Note:

-ErrorAction Ignore - This ignores the exception that would arise if the storage account does not exist Write-Host " " - Double quotes were used to allow for string interpolation since we are connecting strings and variables.

That's all.

I hope this helps

Siglos answered 10/4, 2021 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.