简体   繁体   中英

ERROR: Could not load file or assembly 'Microsoft.Identity.Client | Powershell Azure Function

I am currently working on a powershell script in Azure Function and keep being blocked by this error:

[2021-03-12T16:13:43.484Z] ERROR: Could not load file or assembly 'Microsoft.Identity.Client, Version=4.23.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae'. Le fichier spécifié est introuvable.
[2021-03-12T16:13:43.488Z] 
[2021-03-12T16:13:43.489Z] Exception             : 
[2021-03-12T16:13:43.490Z]     Type       : System.IO.FileNotFoundException
[2021-03-12T16:13:43.492Z]     Message    : Could not load file or assembly 'Microsoft.Identity.Client, Version=4.23.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae'. Le fichier spécifié est introuvable.
[2021-03-12T16:13:43.546Z]     FileName   : Microsoft.Identity.Client, Version=4.23.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae
[2021-03-12T16:13:43.547Z]     TargetSite : 
[2021-03-12T16:13:43.579Z]         Name          : IsTransientException
[2021-03-12T16:13:43.589Z]         DeclaringType : Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory
[2021-03-12T16:13:43.591Z]         MemberType    : Method
[2021-03-12T16:13:43.596Z]         Module        : Microsoft.Azure.PowerShell.Authentication.dll
[2021-03-12T16:13:43.604Z]     StackTrace : 
[2021-03-12T16:13:43.611Z]    at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.IsTransientException(Exception e)
[2021-03-12T16:13:43.612Z]    at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzureAccount account, IAzureEnvironment environment, String tenant, SecureString password, String promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
[2021-03-12T16:13:43.622Z]    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount account, IAzureEnvironment environment, String tenantId, SecureString password, String promptBehavior, Action`1 promptAction)
[2021-03-12T16:13:43.624Z]    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount account, IAzureEnvironment environment, SecureString password, String promptBehavior, Action`1 
promptAction)
[2021-03-12T16:13:43.627Z]    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzureAccount account, IAzureEnvironment environment, String tenantId, String subscriptionId, String subscriptionName, SecureString password, Boolean skipValidation, Action`1 promptAction, String name, Boolean shouldPopulateContextList, Int32 maxContextPopulation)
[2021-03-12T16:13:43.629Z]    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass111_2.<ExecuteCmdlet>b__4()
[2021-03-12T16:13:43.630Z]    at System.Threading.Tasks.Task`1.InnerInvoke()
[2021-03-12T16:13:43.635Z]    at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
[2021-03-12T16:13:43.636Z] --- End of stack trace from previous location where exception was thrown ---
[2021-03-12T16:13:43.638Z]    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
[2021-03-12T16:13:43.643Z] --- End of stack trace from previous location where exception was thrown ---
[2021-03-12T16:13:43.644Z]    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass111_0.<ExecuteCmdlet>b__1(AzureRmProfile localProfile, RMProfileClient profileClient, String name)
[2021-03-12T16:13:43.647Z]    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass118_0.<SetContextWithOverwritePrompt>b__0(AzureRmProfile prof, RMProfileClient client)
[2021-03-12T16:13:43.650Z]    at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
[2021-03-12T16:13:43.651Z]    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3 setContextAction)
[2021-03-12T16:13:43.652Z]    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
[2021-03-12T16:13:43.655Z]    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
[2021-03-12T16:13:43.659Z]    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
[2021-03-12T16:13:43.663Z]    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
[2021-03-12T16:13:43.664Z]    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
[2021-03-12T16:13:43.669Z]     Source     : Microsoft.Azure.PowerShell.Authentication
[2021-03-12T16:13:43.671Z]     HResult    : -2147024894
[2021-03-12T16:13:43.671Z] CategoryInfo          : CloseError: (:) [Connect-AzAccount], FileNotFoundException
[2021-03-12T16:13:43.672Z] FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
[2021-03-12T16:13:43.676Z] InvocationInfo        : 
[2021-03-12T16:13:43.677Z]     MyCommand        : Connect-AzAccount
[2021-03-12T16:13:43.678Z]     ScriptLineNumber : 55
[2021-03-12T16:13:43.679Z]     OffsetInLine     : 1
[2021-03-12T16:13:43.679Z]     HistoryId        : 1
[2021-03-12T16:13:43.680Z]     ScriptName       : C:\Users\nflachaire\CTCPA\GestionnaireStandard\azure-functions\afficherUtilisateurStandard\run.ps1
[2021-03-12T16:13:43.681Z]     Line             : Connect-AzAccount -Credential $cred
[2021-03-12T16:13:43.684Z] 
[2021-03-12T16:13:43.687Z]     PositionMessage  : At C:\Users\nflachaire\CTCPA\GestionnaireStandard\azure-functions\afficherUtilisateurStandard\run.ps1:55 char:1
[2021-03-12T16:13:43.688Z]                        + Connect-AzAccount -Credential $cred
[2021-03-12T16:13:43.690Z]                        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[2021-03-12T16:13:43.690Z]     PSScriptRoot     : C:\Users\nflachaire\CTCPA\GestionnaireStandard\azure-functions\afficherUtilisateurStandard
[2021-03-12T16:13:43.692Z]     PSCommandPath    : C:\Users\nflachaire\CTCPA\GestionnaireStandard\azure-functions\afficherUtilisateurStandard\run.ps1
[2021-03-12T16:13:43.693Z]     InvocationName   : Connect-AzAccount
[2021-03-12T16:13:43.694Z]     CommandOrigin    : Internal
[2021-03-12T16:13:43.695Z] ScriptStackTrace      : at <ScriptBlock>, C:\Users\nflachaire\CTCPA\GestionnaireStandard\azure-functions\afficherUtilisateurStandard\run.ps1: line 55
[2021-03-12T16:13:43.696Z] PipelineIterationInfo : 

My script:

using namespace System.Net

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

# Interact with query parameters or the body of the request.
$data = $Request.Query.Data
if (-not $name) {
    $name = $Request.Body.Data
}

    
$secpassword = ConvertTo-SecureString -String [password] -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList [accountName] , $secpassword   
    
#Connect-PnPOnline -Url $siteurl -Credentials $cred


Connect-MicrosoftTeams -Credential $cred
#$sfbSession = New-CsOnlineSession -Credential $cred
#Import-PSSession $sfbSession

$usersOfCallQueue = Get-CsCallQueue -Identity 5cf715ac-90df-4891-a080-7ba705bf63bb | Select-Object -Property users
$firstUsersFromQueue = ($usersOfCallQueue.Users[0].Guid | Get-CsOnlineUser | Select-Object DisplayName).DisplayName

Disconnect-MicrosoftTeams


Install-Module -Name MSAL.PS 

Connect-AzAccount -Credential $cred

try {
    $storageAccount = Get-AzStorageAccount -ResourceGroupName [RessourceGroupName] -Name [containerName]
    $storageContext = $storageAccount.Context
    $cloudTable = (Get-AzStorageTable –Name [tableName] –Context $storageContext).CloudTable

    #Read the items for the sessionID
    $records = Get-AzTableRow -table $cloudTable -PartitionKey 1
    $body = $records
}
catch {
    $statusRequest = $false
    $errorMessageRequest = "Failure connecting to table for state data, $_"
}


try {
    Add-AzTableRow -table $cloudTable -partitionKey 1 -rowKey $returnData
}
catch {
    $statusRequest = $false
    $errorMessageRequest = "Failure adding item to state table, $_"
}


if ($statusRequest -eq $true) {
    $body = {
        callQueueUsers: firstUsersFromQueue,
        data: $data,
        errorMessageRequest: "Success"
    }
    $status = [HttpStatusCode]::OK
}
else {
    $body = {
        callQueueUsers: $firstUsersFromQueue,
        data: $data,
        errorMessageRequest: $errorMessageRequest
    }
    $status = [HttpStatusCode]::BadRequest
}

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

There should be others error but I cannot debug my code until this error is resolved. My only question is about this missing package error.

The first occurence of the error is at this line:

Connect-AzAccount -Credential $cred

My code from requirement.psd1 files

@{
    # 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.
    'Az' = '5.*'
    'AzTable' = '2.*'
    'MicrosoftTeams' = '2.*'
    'SkypeToolPack' = '3.*'
    'MSAL.PS' = '4.2.1.3'
}

As you can see, I import Microsoft.Identity (MSAL.PS) both way and still get this error. I don't understand. Where should I search for a solution? I have no idea left.

Seems like function app is not registered to use Managed Identity. Managed Identity makes the function app authenticate to Azure resources.

Check out this blog: https://www.rahulpnath.com/blog/how-to-authenticate-azure-function-with-azure-web-app-using-managed-service-identity/#enabling-msi-on-azure-function

I got this error solved by enabling System Managed Identity of my function app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM