[英]Powershell exception stopping execution even with try/catch
我们有一个 powershell 脚本,它在我们的管道中执行,它有一些命令,如果发生任何错误,它们不应停止。 我尝试将脚本块放在try/catch
中,但管道仍然因错误而停止:
这是代码:
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 $_
}
我知道一些解决方法,例如告诉管道继续出错或仅使用-ErrorAction Continue
执行 cmdLet,但对我来说,为什么这不能像我一样工作是没有任何意义的。 至少对于来自 C# 和其他语言的我来说,如果您不想重新抛出异常,那将是默认的行为。
我错过了什么概念?
编辑 1
这是 yaml 的一部分,其中任务失败:
- 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
这是管道的output:
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
因此,为了测试我的假设,我在 PowerShell 中本地编写了这段代码:
$ErrorActionPreference = 'Stop'
try {
& 'az' @('group', 'show', '--name', 'foo')
Write-Host "in try: $LASTEXITCODE"
}
catch {
$_
Write-Host "in catch: $LASTEXITCODE"
}
我得到 output:
Resource group 'foo' could not be found.
in try: 3
因此az
命令失败,退出代码非零,但没有引发错误。 try 块执行良好,我的脚本结束。
如果您在管道中运行它,非零退出代码将导致管道失败。 我的建议是创建某种辅助方法来在 PowerShell 中执行 az CLI 命令,验证$LASTEXITCODE
并自己抛出错误,以便您稍后捕获它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.