Search code examples
powershellgraphazure-functions

Azure Function App (PowerShell) The term 'Connect-MgGraph' is not recognized as a name of a cmdlet, function, script file, or executable program


I created an Azure Function App and choosed the PowerShell language. I would like to use the MS Graph PowerShell module to run the "Get-MgUser" command. I got the error:

The term 'Connect-MgGraph' is not recognized as a name of a cmdlet, function, script file, or executable program.

This is what I did:

requirements.psd1

# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    # To use the Az module in your function app, please uncomment the line below.
    'Microsoft.Graph' = '2.*'
}

run.ps1

using namespace System.Net

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

Import-Module Microsoft.Graph

Connect-MgGraph
$body = Get-MgUser

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

Solution

  • I guess your Connect-MgGraph cmdlet is not recognized.

    Install-Module -Name Microsoft.Graph -Force -Scope CurrentUser -ErrorAction Stop
    

    Instead of just importing the module, try using the full path to import it. Modify your run.ps1 like this

    # Specify the full path to the module
    $modulePath = $env:HOME\site\wwwroot\<YourFunctionAppName>\modules\Microsoft.Graph\<ModuleVersion>
    
    # Import the module
    Import-Module $modulePath
    
    # Use Connect-MgGraph
    Connect-MgGraph
    

    Also add some diagnostic logging to your script to capture more details about what might be going wrong. For eg-

    Write-Host "Attempting to import Microsoft.Graph module"
    Import-Module Microsoft.Graph -ErrorAction Stop
    Write-Host "Microsoft.Graph module imported successfully"