azurepowershellautomationmicrosoft-graph-sdks

Cannot convert the "***************" value of type "System.String" to type "System.Management.Automation.PSCredential"


I'm trying to authenticate to Microsoft Graph from an Azure Automation runbook using the Microsoft Graph PowerShell SDK (v2.28.0).

I have the following Automation Variables defined:

clientId
tenantId
clientSecret

Here’s the code I’m using:

# Load from Automation Variables (these are strings)    
 $clientId     = Get-AutomationVariable -Name "clientId"
 $tenantId     = Get-AutomationVariable -Name "tenantId"
 $clientSecret = Get-AutomationVariable -Name "clientSecret"

# Connect using supported parameter set in Azure Automation
try {
Connect-MgGraph -ClientId $clientId -TenantId $tenantId -ClientSecret $clientSecret -Scopes "https://graph.microsoft.com/.default"
Write-Output "✅ Authentication successful."
}
catch {
    Write-Error "❌ Authentication failed: $($_.Exception.Message)"
}

But I get the following error when the runbook executes:

 Authentication failed: Cannot bind parameter 'ClientSecretCredential'. Cannot convert the "*********************" value of type "System.String" to type "System.Management.Automation.PSCredential".

Solution

  • Newer versions of Connect-MgGraph no longer have -ClientId and -ClientSecret parameters, these have been replaced by a single -ClientSecretCrendential parameter which takes a pscredential as argument.

    Additionally, -Scopes doesn't belong in this parameter set since it's only used for delegated access, it should be removed.

    So, in summary, your actual code should be:

    # Load from Automation Variables (these are strings)
    $clientId = Get-AutomationVariable -Name 'clientId'
    $tenantId = Get-AutomationVariable -Name 'tenantId'
    $clientSecret = Get-AutomationVariable -Name 'clientSecret'
    
    # Connect using supported parameter set in Azure Automation
    try {
        $connectMgGraphSplat = @{
            TenantId               = $tenantId
            ErrorAction            = 'Stop'
            ClientSecretCredential = [pscredential]::new(
                $clientId,
                (ConvertTo-SecureString $clientSecret -AsPlainText -Force))
        }
    
        Connect-MgGraph @connectMgGraphSplat
        Write-Output '✅ Authentication successful.'
    }
    catch {
        Write-Error "❌ Authentication failed: $($_.Exception.Message)"
    }