azureautomation / runbooks

Sample Automation runbooks
MIT License
156 stars 129 forks source link

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

Open JonathanHolvey opened 1 year ago

JonathanHolvey commented 1 year ago

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'
  2. Stop on error:

    $ErrorActionPreference = 'Stop'
    $result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
  3. Catch and explicitly log error:

    $ErrorActionPreference = 'Stop'
    try {
    $result = Invoke-WebRequest -Uri 'https://httpbin.org/status/404'
    }
    catch {
    Write-Error $_
    }
  4. 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.