We have a powershell script that executes in our pipeline and it has a few commands which should not stop if any error occurs. I tried putting the script block inside a try/catch but the pipeline still stopes with error:

This is the code:
try {
az network dns record-set txt add-record `
-g $ResourceGroup `
-n "asuid.$DomainName" `
-v $VerificationId `
-z $Zone
$record = az network dns record-set cname create `
-g $ResourceGroup `
-n $DomainName `
-z $Zone `
-o json | ConvertFrom-Json
az network dns record-set cname set-record `
-g $ResourceGroup `
-n $record.name `
-c $Alias `
-z $Zone
}
catch {
Write-Warning "Creating a DNS record was not possible. Consider creating it by hand or review the error:"
Write-Warning $_
}
I know a few workarounds for that like telling the pipeline to continue on error or just executing the cmdLet with -ErrorAction Continue, but for me it does not make any sense why this wouldn't work the way I did. At least for me who comes from C# and other languages, that would the default bahavior if you don't want to rethrow the exception.
What concept am I missing?
EDIT 1
Here is the part of the yaml with the task which is failling:
- task: AzureCLI@2
name: create_dns_record
displayName: "Creates a DNS record for CNAME and TXT on DNS Zone"
inputs:
azureSubscription: 'some-azure-subscription'
scriptType: 'pscore'
scriptLocation: 'inlineScript'
inlineScript: |
. $(System.DefaultWorkingDirectory)/cd/NewDNSRecordSet.ps1
New-DNSRecordSet `
-ResourceGroup 'rg_zones' `
-DomainName '$(domain_name)' `
-Zone '$(dns_zone)' `
-VerificationId '$(verificationId)' `
-Alias '$(defaultHostName)' # verificationId and defaultHostName as output from the task CreateInfrastructure.ps1
Here is the output of the pipeline:
Creating DNS Recordset for 'mytest.dev' zone.
Adding txt record: asuid.mytest
ResourceNotFoundError: Resource group 'rg_zones' could not be found.
Creating CNAME record: mytest
ResourceNotFoundError: Resource group 'rg_zones' could not be found.
WARNING: Creating a DNS record was not possible.
##[error]Script failed with exit code: 1
So to test my assumption I wrote this bit of code locally in my PowerShell:
$ErrorActionPreference = 'Stop'
try {
& 'az' @('group', 'show', '--name', 'foo')
Write-Host "in try: $LASTEXITCODE"
}
catch {
$_
Write-Host "in catch: $LASTEXITCODE"
}
I get the output:
Resource group 'foo' could not be found.
in try: 3
So the az command failed, with a non-zero exit code but it didn't throw an error. The try block executes fine and my script ends.
If you run this in a pipeline, the non-zero exit code would result in the pipeline failing. My proposition is to create some kind of helper method for executing az CLI commands in PowerShell, verify the $LASTEXITCODE and throw an error yourself so you could catch it later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With