【问题标题】:Azure CLI Exception HandlingAzure CLI 异常处理
【发布时间】:2018-12-27 18:56:48
【问题描述】:

我已在本地系统上安装了 azure cli,并且可以在 Windows Powershell 中运行 azure cli 命令。当我运行任何不正确或抛出任何异常的命令时,我可以在控制台上看到它。但是如何使用 Try...Catch 捕获此异常。我想在 powershell 脚本中使用 try..catch 来处理异常。

请帮帮我。

代码sn-p:

假设我的 ClientSecret 错误,那么下面的命令将通过异常,我如何在 Catch 块中捕获它??

 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

【问题讨论】:

    标签: powershell azure command-line-interface


    【解决方案1】:

    最新版本的 CLI 支持全局参数 --only-show-errors,它将禁止预览消息。因此,您可以像这样修改 Avshalom 的答案来解决 UNeverNo 提出的问题:

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

    【讨论】:

      【解决方案2】:

      在常规 Powershell 命令中,您可以使用 CommonParameter -ErrorAction Stop 但对于 AzureCli az 命令,我认为您可以使用简单的 if 语句:

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

      或者在登录尝试后使用$?自动变量检查最后的退出状态:

      if (!$?) {"Error"}
      

      【讨论】:

      • 不幸的是,这并非在所有情况下都有效。我尝试在 devops 中使用az rest,因为它处于预览状态,它会输出一条消息,指出“此命令处于预览状态。它可能会在未来的版本中更改/删除。”所以我的任务失败了,尽管$? 返回 $true。
      【解决方案3】:

      这么晚才回答是为了帮助面临同样问题的其他人。尝试将输出存储在参数中并检查它是否为空。由于 azure 命令以 json 格式给出输出,我们可以使用:

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

      【讨论】:

        【解决方案4】:

        尝试使用--query 运算符来检查您需要的东西。例如,如果您查询启用状态或其他内容,Avshalom 的答案可能是正确的。我在某些地方做类似的事情:

        # 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'
        }
        

        【讨论】:

          【解决方案5】:

          我需要检查特定的 Apim Api 版本集是否存在,没有可用的标准“存在”命令。以下是我设法得到结果的方法。

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

          如果版本集存在,$exists 将返回 true。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-10-02
            • 2020-11-13
            • 1970-01-01
            • 1970-01-01
            • 2017-09-18
            • 1970-01-01
            • 2016-09-08
            相关资源
            最近更新 更多