Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Errors not logged when using $ErrorActionPreference = 'Stop' in PowerShell #105

Open
JonathanHolvey opened this issue Nov 15, 2023 · 0 comments

Comments

@JonathanHolvey
Copy link

I have two requirements for error handling in a PowerShell runbook:

  1. Execution stops with the status 'Failed' when an error occurs; and
  2. 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.

  1. Default behaviour:
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
  1. Stop on error:
$ErrorActionPreference = 'Stop'
$result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
  1. Catch and explicitly log error:
$ErrorActionPreference = 'Stop'
try {
    $result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
}
catch {
    Write-Error $_
}
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant