How to pass a JSON document from Azure Service Bus to Azure Functions (using PowerShell)

Azure Functions have many input bindings built-in (HTTP, Service Bus, etc.). It is common to have a message on the Azure Service Bus be a JSON document.

curl -X POST -H "Content-Type: application/json" -H "Authorization: SharedAccessSignature ..." -d '{ "UserPrincipalName": "dwight.k.schrute@dunder-mifflin.com"}' https://sb-serviceBusTest-ussc-dev.servicebus.windows.net/sendMessage/messages

However, you have to be explicit about the type of the input parameter. If you use [string] as the input parameter type, you will not be able to retrieve the JSON data.

param([string] $message, $TriggerMetadata)

Write-Information ("Print: {0}" -f $message)
Write-Information ("Type: {0}" -f $message.GetType())
Write-Information ("UPN: {0}" -f $message.UserPrincipalName)

We can see the “data” stored in this variable is System.Collections.Hashtable and the parameter is of type System.String. We can also see that we can’t reference the JSON data inside the parameter (because it is not a HashTable, it is a string).

2023-03-28T13:29:11Z   [Information]   INFORMATION: Print: System.Collections.Hashtable
2023-03-28T13:29:11Z   [Information]   INFORMATION: Type: System.String
2023-03-28T13:29:11Z   [Information]   INFORMATION: UPN: 

Instead, you should specify the type of input parameter as either [System.Collections.HashTable] or [object].

param([System.Collections.HashTable] $message, $TriggerMetadata)

Write-Information ("Print: {0}" -f $message)
Write-Information ("Type: {0}" -f $message.GetType())
Write-Information ("UPN: {0}" -f $message.UserPrincipalName)

Now we can see that the JSON document was correctly passed through the Service Bus to the PowerShell script running in Azure Functions.

2023-03-28T13:36:23Z   [Information]   INFORMATION: Print: System.Collections.Hashtable
2023-03-28T13:36:23Z   [Information]   INFORMATION: Type: System.Collections.Hashtable
2023-03-28T13:36:23Z   [Information]   INFORMATION: UPN: dwight.k.schrute@dunder-mifflin.com

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *