Errors not logged when using $ErrorActionPreference = 'Stop' in PowerShell
JonathanHolvey opened this issue · 0 comments
JonathanHolvey commented
I have two requirements for error handling in a PowerShell runbook:
- Execution stops with the status 'Failed' when an error occurs; and
- The error is visible in the runbook job's error logs
I've tried several minimal scripts while attempting to meet these requirements, however none satisfy both together.
- Default behaviour:
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
- Stop on error:
$ErrorActionPreference = 'Stop'
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
- Catch and explicitly log error:
$ErrorActionPreference = 'Stop'
try {
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
}
catch {
Write-Error $_
}
- Catch and explicitly throw error:
$ErrorActionPreference = 'Stop'
try {
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
}
catch {
Throw $_
}
Practically, catching and throwing the same error shouldn't be any different to not catching it in the first place (as in scenario 2), however I've included it here for completeness.
Results
Scenario | Runbook status | Error logged | Requirements |
---|---|---|---|
1. Default behaviour | Completed | Yes | ❌ ✔️ |
2. Stop on error | Failed | None found | ✔️ ❌ |
3. Catch and log | Failed | None found | ✔️ ❌ |
4. Catch and throw | Failed | None found | ✔️ ❌ |
Is it possible to set up a PowerShell runbook that will satisfy both of my requirements?
I'm using a PowerShell 5.1 runbook running on 'Azure' in the Australia East region.