Use PowerShell Modules in Azure Functions

Page content

Lately, I have been working on some self-service tooling so that the employees can do specific tasks themselves, like updating members of a Shared Mailbox instead of creating a ticket and asking IT to do this. To build this solution, we have developed an Azure Function with API management as the back-end and a PowerApp as the front-end.

Our team uses PowerShell a lot, and the easiest way to communicate with Exchange Online is using PowerShell.

Our setup

As mentioned, we have built the following components

  • Azure Function 4 with PowerShell
  • API management gateway connected to the Azure Function
  • PowerApp consuming the API management connector

Azure Function

All functions that we have are HTTP-triggered and have a specific task. We are using VS code and Azure DevOps to follow development best practices. Within Azure Functions, we have created a deployment slot where we deploy and test out the functions we make before pushing them into production. This way, we do not interfere with or break anything currently in production.

Modules

In Azure Functions, there are two ways of adding PowerShell modules: you upload the module content in a folder called “Modules” that is on the same level as each function, or you use the ManagedDependency. We went for the ManagedDependency as we will only use the Modules in the PowerShell Gallery. The significant benefit of using ManagedDependency is that you do not need to maintain the modules in your project. A drawback is that you can only add ten modules in the ManagedDependency. As we are only using three modules, this is no issue.

ManagedDependency

Using the ManagedDependency requires you to update two files.

  • host.json
  • requirements.psd1

You need to add the following three lines in “host.json.”

"managedDependency": {
    "enabled": true
  }

In “requirements.psd1”, there is a list of modules where you can add the required modules. Here you can use the following syntax “MajorNumber.*” or the exact version number. I have encountered that for some versions of the ExchangeOnline module, the reference to the JWT DLL"s incorrect, and here I can advise you to use the exact version number.

Authentication

With the availability of Managed Identity, this is easy. Enable managed Identity and connect to Exchange Online using this line of code; in the configuration, you only need to add the tenant name in the format “tenantdomain.onmicrosoft.com”

Connect-ExchangeOnline -ManagedIdentity -Organization $env:AzureAD_Tenant

We have this in the “profile.ps1” instead of each module because there can only be three simultaneous connections to Exchange Online.

When you also need a connection to the Microsoft Graph and want to use Managed Identity, you need to use the “2.0.0-preview” version or later.

Connect-MgGraph -Identity

References