Azure Functions - In Powershell

Copper Contributor



Can someone please provide some guidance regarding writing azure functions with Powershell.

Essentially I would like to connect-mgGraph and display a user attribute.


1. I have a function app built

2. The profile file looks like 

if ($env:MSI_SECRET) {
    Disable-AzContextAutosave -Scope Process | Out-Null
    Connect-AzAccount -Identity
3. The requirements.psd1 file looks like:
    # For latest supported version, go to ''.
    # To use the Az module in your function app, please uncomment the line below.
    'Az' = '9.*'
    'Microsoft.Graph.Authentication' = '1.*'
    'Microsoft.Graph.Users' = '1.*'
So what is the best way to connect to MGGraph?
1 Reply



Your "profile.ps1" and "requirements.psd1" are looking fine to load the "Microsoft.Graph.Authentication" & "Microsoft.Graph.Users" modules and authenticate using the "System Managed Identity".

By default the Azure Function "System Managed Identity" is connecting to the scope.

The "Connect-MgGraph" command requires a token from the scope .


Here's an example of an Azure  Function that is acquiring such a token for the "System Assigned Managed Identity" and authenticate:

(don't forget to give the correct permissions for the "System Assigned Managed Identity" on Azure Active Directory)


using namespace System.Net

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

function Get-AzToken {
    param (
        [Parameter(Mandatory = $true)]
    $Context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
    $Token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, $ResourceUri).AccessToken
    if ($AsHeader) {
        return @{Headers = @{Authorization = "Bearer $Token" } }
    return $Token

$Token = Get-AzToken -ResourceUri ''
Connect-MgGraph -AccessToken $Token
$usersJson = (Get-MgUser -All | Format-List  ID, DisplayName, Mail, UserPrincipalName | convertto-json -depth 100 ) 

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $usersJson



For more information to acquire the token, look ar the Stack Overflow discussion over HERE.