A little gotcha with Azure PowerShell Functions

Recently, I had a great use case for using the PowerShell support within Azure Functions.  During development, I encountered a weird behaviour on the error handling side.  In this short blog, I want to share this experience with you.  Hopefully, it can save you some troubleshooting time!

Starting point

My initial function looked like this, based on the samples in the developer guide.  Even though my code was not working correctly, the Azure Function kept on returning an HTTP 200.  I would have expected an internal server error.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# My code that was not working correctly

# Return output HTTP response
$status = [HttpStatusCode]::OK

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = $status
    Body = $body

Adding try/catch

My next attempt, was to add a try catch.  In case of an exception, I return an internal server error that includes the exception detail.  However, still no error is returned.  Despite all my efforts, I kept on receiving an HTTP 200 when invoking the PowerShell Function.

   # My code that was not working correctly
   $body = $_.Exception.Message
   $status = [HttpStatusCode]::InternalServerError

The solution

After some Googling around, this blog helped me out.  PowerShell has terminating and non-terminating errors.  A catch block is only handling terminating errors.  In my use case, I want to handle every error.  This can be done by adding the following statement to your script.  This tells PowerShell to treat every error as a terminating one.

$ErrorActionPreference = "Stop"

From now on, I received clear error messages with HTTP status 500.


I used this error handling statement already many times before, but I forgot to use it within the context of Azure Functions.  Azure Functions supports multiple languages, each of them come with their own specifics.  This is one of them, that I won’t forget anymore!




Your Azure Coach is specialized in organizing Azure trainings that are infused with real-life experience. All our coaches are active consultants, who are very passionate and who love to share their Azure expertise with you.