Search code examples
powershellazure-powershellazure-cli

Powershell How to Handle Az Cli in a Try Catch Block


I have the following code...

When the resource is not found an error is raised but the code continues to run...not sure why?

 try{
              
              $state=$(az synapse sql pool show --name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME --query "status")

              Write-Host("State = $state")

              if($state -match "Paused")
              {
                Write-Host("Resume Pool xxx")
                
                az synapse sql pool resume --name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME

                az synapse sql pool wait --sql-pool-name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME --custom "state==Online"
              };
          
            
            }
            catch
            {
              Write-Host("Handle error - no need to do anything....")
            }

Solution

  • A try-catch block only catches terminating errors. Non-terminating errors, like the one thrown by the az command in this case, are not caught and do not stop the execution of the script. Use the $ErrorActionPreference variable and set to $ErrorActionPreference = "Stop" at the beginning of your script.

    $ErrorActionPreference = "Stop"
    
    try {
        $state=$(az synapse sql pool show --name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME --query "status")
    
        Write-Host("State = $state")
    
        if($state -match "Paused") {
            Write-Host("Resume Pool xxx")
            az synapse sql pool resume --name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME
            az synapse sql pool wait --sql-pool-name $DB_NAME --resource-group $RG_NAME --workspace-name $WKSPC_NAME --custom "state==Online"
        }
    }
    catch {
        Write-Host("Handle error - no need to do anything....")
    }