Valter Silva
Valter Silva

Reputation: 16656

How to catch exceptions on PowerShell?

I'm running this PowerShell script twice, almost simultaneously:

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

Which throws this exception:

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

I need to avoid 2 deployments were running at the same time to the same resource. So, I'm trying to catch the exception and then later force to run the AzureRM provisioning sequentially.

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
}

However, I had no success so far. I'm new to PowerShell scripting.

Upvotes: 2

Views: 5220

Answers (1)

colsw
colsw

Reputation: 3336

The error thrown by New-AzureRmResourceGroupDeployment is Non-Terminating and will not trigger a Try{}catch{} statement as is.

By adding -ErrorAction Stop to the end of the Statement inside the Try block (before or after the -Force), you can force it to become a terminating error, which will trigger the Catch statement.

Upvotes: 12

Related Questions