如何在PowerShell上捕获异常?

时间:2017-05-18 14:56:51

标签: powershell azure

我几乎同时运行这个PowerShell脚本两次:

#Provision Resource Group and all Resources within ARM Template
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
-TemplateFile $TemplateFile `
-Mode Incremental `
-TemplateParameterFile $TemplateParametersFile @ExtraParameters `
-keyVaultAccessPolicies @($keyVaultPoliciesList) `
-Force

抛出此异常:

VERBOSE: 16:48:48 - Template is valid.
New-AzureRmResourceGroupDeployment : Unable to edit or replace deployment 'DeploymentTemplate': previous deployment from '5/18/2017 2:48:47 PM' is still active (expiration time is '5/25/2017 2:48:46 PM'). Please see https://aka.ms/arm-deploy for usage details.
At L:\Source\Start-ArmEnvironmentProvisioning.ps1:274 char:1
+ New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [New-AzureRmResourceGroupDeployment], CloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet

我需要避免2个部署同时运行到同一个资源。所以,我试图捕获异常,然后强制顺序运行AzureRM配置。

Try
{
  #Provision Resource Group and all Resources within ARM Template
  $params = @{'Name' = $ResourceGroupName;
              'ResourceGroupName' = $ResourceGroupName;
              'TemplateFile' = $TemplateFile;
              'TemplateParameterFile' = $TemplateParametersFile;
              'keyVaultAccessPolicies' = @($keyVaultPoliciesList) }
  New-AzureRmResourceGroupDeployment @params -Force
}
Catch
{
  $ErrorMessage = $_.Exception.Message
  $FailedItem = $_.Exception.ItemName
  Write-Error "We failed to read file $FailedItem. The error message was $ErrorMessage"
  Break
}

然而,到目前为止我没有成功。我是PowerShell脚本的新手。

1 个答案:

答案 0 :(得分:7)

New-AzureRmResourceGroupDeployment引发的错误为Non-Terminating,不会按原样触发Try{}catch{}语句。

-ErrorAction Stop添加到Try块内{在-Force之前或之后)的语句末尾,可以强制它成为终止错误,这将触发Catch声明。