Share via

Meeting "ERROR: Run Connect-AzAccount to login. Exception : Type : System.Management.Automation.PSInvalidOp" In Azure powershell function when run "Connect-AzAccount -Environment AzureChinaCloud -Credential $Cred)"

Jack Chen 0 Reputation points
2024-08-15T01:20:23.8166667+00:00

Our China production environmen powershell function APP have ran normoally long time but in t report error suddenly. we have tried change Az module to some older and newer version, and rewite runtime version, but stll report the same error. Please help troubleshooting and resolve it.

Sample code as below (it runs successfully in local Env ) :

param($Timer)
$password="xxxxx"
$Creds = ((New-Object System.Management.Automation.PSCredential("******@xxx.xxxx.onmschina.cn",(ConvertTo-SecureString $password -AsPlainText -Force))))

foreach ($Cred in $Creds)
{
     [void](Connect-AzAccount -Environment AzureChinaCloud  -Credential $Cred);
    $Subscriptions = Get-AzSubscription
foreach ($subscription in $subscriptions){ 	
    $subscription 
}
}

Error details:

ERROR: Run Connect-AzAccount to login. Exception : Type : System.Management.Automation.PSInvalidOperationException ErrorRecord : Exception : Type : System.Management.Automation.ParentContainsErrorRecordException Message : Run Connect-AzAccount to login. HResult : -2146233087 CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException FullyQualifiedErrorId : InvalidOperation TargetSite : Name : get_DefaultContext DeclaringType : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet MemberType : Method Module : Microsoft.Azure.PowerShell.Clients.ResourceManager.dll Message : Run Connect-AzAccount to login. Source : Microsoft.Azure.PowerShell.Clients.ResourceManager HResult : -2146233079 StackTrace : at Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet.get_DefaultContext() at Microsoft.Azure.Commands.Profile.GetAzureRMSubscriptionCommand.BeginProcessing() at System.Management.Automation.Cmdlet.DoBeginProcessing() at System.Management.Automation.CommandProcessorBase.DoBegin() CategoryInfo : InvalidOperation: (:) [Get-AzSubscription], PSInvalidOperationException FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.Profile.GetAzureRMSubscriptionCommand InvocationInfo : MyCommand : Get-AzSubscription ScriptLineNumber : 28 OffsetInLine : 22 HistoryId : 1 ScriptName : C:\home\site\wwwroot\TimerTrigger1\run.ps1 Line : $Subscriptions = Get-AzSubscription PositionMessage : At C:\home\site\wwwroot\TimerTrigger1\run.ps1:28 char:22 + $Subscriptions = Get-AzSubscription + ~~~~~~~~~~~~~~~~~~ PSScriptRoot : C:\home\site\wwwroot\TimerTrigger1 PSCommandPath : C:\home\site\wwwroot\TimerTrigger1\run.ps1 InvocationName : Get-AzSubscription CommandOrigin : Internal ScriptStackTrace : at 
Azure Functions
Azure Functions

An Azure service that provides an event-driven serverless compute platform.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Amira Bedhiafi 41,386 Reputation points MVP Volunteer Moderator
    2026-04-25T17:47:53.0833333+00:00

    Hello !

    Thank you for posting on MS Learn Q&A.

    You can reply like this:

    The error is raised by Get-AzSubscription, not directly by Connect-AzAccount. That means the Function runtime has no valid Az context at the moment Get-AzSubscription runs.

    In a PS Azure Function, I would avoid using a user/password credential like this:

    Connect-AzAccount -Environment AzureChinaCloud -Credential $Cred
    

    That pattern is fragile in non-interactive automation. If MFA, Conditional Access, password policy, token/cache behavior, tenant selection, or an Az.Accounts change affects the login, Connect-AzAccount may not establish a usable context and the next command fails with:

    Run Connect-AzAccount to login
    

    If you check the doc below, Connect-AzAccount you will find that credentialvbased user login only works when MFA is not enabled otherwise interactive login or service principal authentication should be used. Connect-AzAccount supports both managed identity login and service principal login.

    https://learn.microsoft.com/en-us/powershell/module/az.accounts/connect-azaccount?view=azps-15.5.0

    For an Azure Function, the fix is usually managed identity:

    param($Timer)
    $ErrorActionPreference = "Stop"
    Disable-AzContextAutosave -Scope Process | Out-Null
    $TenantId = "<tenant-id>"
    $SubscriptionId = "<subscription-id>"
    Connect-AzAccount `
        -Environment AzureChinaCloud `
        -Identity `
        -Tenant $TenantId `
        -ErrorAction Stop | Out-Null
    Set-AzContext -Subscription $SubscriptionId -Tenant $TenantId -ErrorAction Stop | Out-Null
    $Subscriptions = Get-AzSubscription -ErrorAction Stop
    foreach ($subscription in $Subscriptions) {
        Write-Host $subscription.Name
    }
    

    Then assign the Function app managed identity the required RBAC role, for example reader, at the subscription or resource group scope.

    If managed identity is not possible, use a service principal not a user password:

    param($Timer)
    $ErrorActionPreference = "Stop"
    Disable-AzContextAutosave -Scope Process | Out-Null
    $TenantId = "<tenant-id>"
    $ApplicationId = "<app-client-id>"
    $ClientSecret = $env:CLIENT_SECRET
    $SubscriptionId = "<subscription-id>"
    $SecurePassword = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
    $Credential = [System.Management.Automation.PSCredential]::new($ApplicationId, $SecurePassword)
    Connect-AzAccount `
        -Environment AzureChinaCloud `
        -ServicePrincipal `
        -TenantId $TenantId `
        -Credential $Credential `
        -ErrorAction Stop | Out-Null
    Set-AzContext -Subscription $SubscriptionId -Tenant $TenantId -ErrorAction Stop | Out-Null
    Get-AzSubscription -ErrorAction Stop
    

    Azure China documentation shows the same service principal pattern with Connect-AzAccount -Environment AzureChinaCloud -ServicePrincipal -TenantId ... -Credential ....

    https://docs.azure.cn/en-us/databricks/dev-tools/auth/azure-powershell-login

    0 comments No comments

Your answer

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