MgGraph with Azure Automation Runbook

Mattps 5 Reputation points
2024-01-24T11:25:25.9866667+00:00

Hi,

I am trying to use MgGraph in an Azure runbook but keep hitting a dead end and would appreciate any suggestions. I have the MgGraph modules loaded in the Automation account and credentials saved in the credentials section of the automation account. To test I am just trying to connect to MgGraph first but failing to even do this. This is my PowerShell code:

$Cred = Get-AutomationPSCredential -Name "#######"
Install-Module -Name Microsoft.Graph
Connect-MgGraph -ClientID $TAECred -TenantID "########-####-####-####-############"

The error I receive is:

Connect-MgGraph : The term 'Connect-MgGraph' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:5 char:1 + Connect-MgGraph -ClientID $Cred -TenantID "########-####-####-#### ... + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Connect-MgGraph:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

Any ideas?

Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,349 questions
{count} votes

1 answer

Sort by: Most helpful
  1. EPNAdam 50 Reputation points
    2024-08-06T14:29:45.3233333+00:00

    Hi,

    Please see this: https://docs.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation#authenticate-access-with-system-assigned-managed-identity

    Tested in my automation account running PowerShell 7.2 in a runtime environment with the Az and Microsoft.Graph.Authentication modules installed.

    Code which connects to Azure and Microsoft.Graph using managed identity:

    Disable-AzContextAutosave -Scope Process    # Ensures you do not inherit an AzContext in your runbook
    $azureContext = (Connect-AzAccount -Subscription $SubScriptionId -Tenant $TenantId -Identity).context
    
    Write-Output "-> Setting context"
    $azureContext = Set-AzContext -SubscriptionName $azureContext.Subscription -DefaultProfile $azureContext
    
    Write-Output "`n+ Connecting to Graph (Managed Identity)"
    Connect-MgGraph -Identity -NoWelcome
    

    Output:

    User's image

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.