我有一个包含一些错误处理的Azure功能(PowerShell)。如果出现错误,我会执行几个简单的操作,然后我希望停止执行,但这不起作用; PowerShell忽略了exit 1
命令并继续执行。
try{
$metrics = Get-AzureMetrics -BearerToken $bearer_token -SubscriptionId $env:HC_SubscriptionId -ResourceGroup $env:HC_ResourceGroup -ResourceType $env:HC_ResourceType -ResourceName $env:HC_ResourceName
} catch {
$failure = $_.Exception.Message
Write-Output "[ERROR] Failed to GET metrics from Azure Monitor. $failure"
Invoke-LogToSplunk -EventHost "bvt-processevnts" -Source $env:HealthCheckFunctionName -Message "Failed to GET metrics from Azure Monitor. $failure" -Severity "ERROR" -SplunkUri $env:SplunkUrl -AccessToken $env:SplunkToken | Out-Null
exit 1
}
请注意,exit 1
在本地测试时有效,只有在我将其作为Azure功能运行时才能看到此问题。我还试过了Return
和Break
,但这些命令也被忽略了。
我考虑用exit 1
替换$error_occurred = $true
,然后在if
语句中嵌套进行命令(见下文)。但是,如果可能的话,我希望避免这种情况,因为从长远来看管理起来比较困难,而团队中可能需要查看/编辑Azure功能的其他人则不太清楚。< / p>
if ( ! ( $error_occurred ) ) {
# Other commands
}
所以我的问题(希望)很简单;如何告诉Azure功能停止执行?
答案 0 :(得分:1)
此解决方案可能不符合您的需求,但您可以尝试这样的事情吗?
Function Get-AzureMetricsOrFail ($bearer_token) {
try{
$metrics = Get-AzureMetrics -BearerToken $bearer_token -SubscriptionId $env:HC_SubscriptionId -ResourceGroup $env:HC_ResourceGroup -ResourceType $env:HC_ResourceType -ResourceName $env:HC_ResourceName
} catch {
$failure = $_.Exception.Message
Write-Output "[ERROR] Failed to GET metrics from Azure Monitor. $failure"
Invoke-LogToSplunk -EventHost "bvt-processevnts" -Source $env:HealthCheckFunctionName -Message "Failed to GET metrics from Azure Monitor. $failure" -Severity "ERROR" -SplunkUri $env:SplunkUrl -AccessToken $env:SplunkToken | Out-Null
}
return $metrics
}
$metrics_result = Get-AzureMetricsOrFail -bearer_token 'some_token'
if($metrics_result) {
'Successfully obtained Azure Metrics'
# Rest of code
} else {
'Failed getting Azure Metrics.'
}
或者,也许只想移动Exit语句?
try{
$metrics = Get-AzureMetrics -BearerToken $bearer_token -SubscriptionId $env:HC_SubscriptionId -ResourceGroup $env:HC_ResourceGroup -ResourceType $env:HC_ResourceType -ResourceName $env:HC_ResourceName
} catch {
$failure = $_.Exception.Message
Write-Output "[ERROR] Failed to GET metrics from Azure Monitor. $failure"
Invoke-LogToSplunk -EventHost "bvt-processevnts" -Source $env:HealthCheckFunctionName -Message "Failed to GET metrics from Azure Monitor. $failure" -Severity "ERROR" -SplunkUri $env:SplunkUrl -AccessToken $env:SplunkToken | Out-Null
}
if(!($metrics)) {
exit
}