4
votes

I have installed the azure cli on my local system and I am able to run the azure cli commands in Windows Powershell. When I run any command which is not correct or throwing any exception, I am able to see it on the console. But how can I capture this exception using Try...Catch . I want to handle the exception using try..catch in powershell script.

Please help me on this.

code snippet:

Suppose my ClientSecret is wrong then the below command will through an exception, how can I capture this in Catch block??

 Try
    {

     $TenantId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' 
     $ClientId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' 
     $ClientSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

     az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId 

    }
    Catch 
    {
        $ErrorMessage = $_.Exception.Message
        Write-Output $ErrorMessage 
    }

this is the snapshot of the issue

5

5 Answers

2
votes

More recent versions of the CLI support a global parameter --only-show-errors which will suppress preview messages. So you could amend the Avshalom answer like this to solve the issue UNeverNo raised:

if (az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId --only-show-errors)
{
   "Success"
}
else {"Error"}
1
votes

Answering that late to help others facing the same issue. Try to store the output in a parameter and check if it is null or not. As azure commands give the output in json format, we can use:

$output = az login -u "username" -p "password" | ConvertFrom-Json
if (!$output) {
    Write-Error "Error validating the credentials"
    return
}
0
votes

In regular Powershell commands you can use the CommonParameter -ErrorAction Stop But for the AzureCli az command i think you can use a simple if statement:

if (az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId)
{
   "Success"
}
     else {"Error"}

Or check the last exit state using the $? Automatic variable after the login attempt:

if (!$?) {"Error"}
0
votes

Try using the --query operator to check for things you need. For example, Avshalom's answer might be correct if you query for state enabled or something. I am doing similar things in some places:

# Create the Web App if it does not already exist
if(-Not (az webapp show --name $webAppName --resource-group $resourceGroupName))
{
    az webapp create --name $webAppName --resource-group $resourceGroupName --plan $servicePlanName --tags 'displayName=WebApp'
}
0
votes

I had a requirement to check if a particular Apim Api Version Set exists or not, for which there are no standard "exists" commands available. Below is how I managed to get the result.

$result = az apim api versionset list --resource-group MyResourceGroup --service-name MyApim --query "[?name=='MyVersionSet']" | ConvertFrom-Json

$exists = $result.Length -gt 0

$exists will return true if the version set exists.