Jack Smith
Jack Smith

Reputation: 63

display custom error message in Azure powershell and exit

I am trying to get the list of storages name for a specific subscription using powershell. If I have the correct subscription name, I get the result but if there is some mistype then I get this error:

Select-AzSubscription : Please provide a valid tenant or a valid subscription. Select-AzSubscription -SubscriptionName $subName CategoryInfo : CloseError: (:) [Set-AzContext], ArgumentException FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand

What would be the best option to handle the error message and exit out from the script with a message "Couldn't find the subscription". Here is the powershell code:

###Set a subscription name
$subName = "Test SubscriptionName"

Select-AzSubscription -SubscriptionName $subName

### Select storage accounts based for above subscription
$sAccount = Get-AzStorageAccount | select StorageAccountName
$sAccount

Upvotes: 1

Views: 687

Answers (3)

Jack Smith
Jack Smith

Reputation: 63

I was able to solve it using try-catch method. Here is the solution:

 $subName = "Test SubscriptionName"

Try { 
     Select-AzSubscription -SubscriptionName $subName -ErrorAction Stop
        #Select storage accounts based for above subscription
         $sAccount = Get-AzStorageAccount | select StorageAccountName
          $sAccount
         } 
Catch{
        Write-Host  $_.Exception.Message
     }

Upvotes: 1

Mike Smith - MCT
Mike Smith - MCT

Reputation: 1231

You can just do a null test:

$sub = Select-AzSubscription -SubscriptionName $subName -ErrorAction SilentlyContinue
if ($sub -eq $null) 
  { 
    "Couldn't find the subscription"
    ## Add you exit code here!
  }  
else
  { "Good subname" }

Upvotes: 1

Ivan Glasenberg
Ivan Glasenberg

Reputation: 29995

The better solution should be use the scripts below:

$subName = "Test SubscriptionName"

try{ 
     Select-AzSubscription -SubscriptionName $subName -ErrorAction Stop        
    } 
catch [System.ArgumentException]{
        Write-Host "Couldn't find the subscription"

        #use exit to exit the script
        exit
     }

#Select storage accounts based for above subscription      
$sAccount = Get-AzStorageAccount | select StorageAccountName
$sAccount

Upvotes: 1

Related Questions