1

Running this script in Azure:

Write-Host "Running ps_example.ps1"

$resourceGroupName = 'myGroupName'
$storageName = "psexample"
$storageType = "Standard_LRS"
$location = "centralus"

if (Test-AzureName -Storage $storageName) {
    Write-Host "Use existing storage account - $storageName"
} Else {
    Write-Host "Make new storage account - $storageName"
    New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageName -Type $storageType -Location $location
}

The first run shows:

Running ps_example.ps1
Make new storage account - psexample

The second run shows:

Running ps_example.ps1
Make new storage account - psexample
The storage account named psexample is already taken.

Why? That would seem to indicate that if (Test-AzureName -Storage $storageName) always returns false.

If I tell Azure to use powershell 1, the version is 1.113.5. Requesting version 2.0 results in 2.0.11. The behavior is the same for both.

EDIT:

Running this:

$result = Test-AzureName -Storage $storageName
Write-Host $result

always prints False, whether psexample exists or not.

Don Branson
  • 13,631
  • 10
  • 59
  • 101

1 Answers1

1

You are combining RM and SM cmdlets in Azure. Test-AzureName is a Service Management cmdlet, while New-AzureRmStorageAccount is a Resource Manager cmdlet.

You may want to try to use

if ((Get-AzureRmStorageAccountNameAvailability -Name $storageName).NameAvailable) {
    Write-Host "Make new storage account - $storageName"
    New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageName -Type $storageType -Location $location
} Else {
    Write-Host "Use existing storage account - $storageName"
}

to check for the name or you can create your storage account with:

New-AzureStorageAccount

Depending on what you want to use, SM or RM.

Don Branson
  • 13,631
  • 10
  • 59
  • 101
Norman
  • 3,279
  • 3
  • 25
  • 42
  • Interesting. I had tried user891818's answer to https://stackoverflow.com/questions/30076601/azure-powershell-check-to-see-if-resource-exists, which doesn't work. Is his if statement malformed? – Don Branson Apr 26 '18 at 13:54
  • @DonBranson That answer looks good - when paying attention to the comment. So should be something like this: if((Get-AzureRmStorageAccountNameAvailability -Name $storageName) -eq $True) { New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageName -SkuName Standard_LRS } – Norman Apr 26 '18 at 14:19
  • Get-AzureRmStorageAccountNameAvailability doesn't return a boolean, it returns a Microsoft.Azure.Management.Storage.Models.CheckNameAvailabilityResult, which contains a boolean. checking to see if that works... – Don Branson Apr 26 '18 at 15:01
  • 1
    I found that NameAvailable does the trick. I edited your answer to show that, but please feel free to adjust it as you see fit. – Don Branson Apr 26 '18 at 20:33