Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.21k stars 3.82k forks source link

[Polyglot notebook] Clear-AzContext: Method not found: Microsoft.Identity.Client.PublicClientApplicationBuilder #22822

Closed MvanderBoom closed 1 year ago

MvanderBoom commented 1 year ago

Description

Hallo all,

I'm trying to do some Azure automation from within a Polyglot Notebook (.Net Interactive kernel) using VS Code, I have the following powershell script in a code block:

$AzureEnvironment = 'AzureCloud'
$AzureAccount = '<snip>'
$AzureTenant = '<snip>'
$AzureSubscription = '<snip>'

$AzContext = Get-AzContext

if (-not $AzContext)
{
    Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAccount -TenantId $AzureTenant -SubscriptionId $AzureSubscription
}

This generates the following error:

Connect-AzAccount: Method not found: 'Void Azure.Core.TokenRequestContext..ctor(System.String[], System.String, System.String, System.String, Boolean)'.
Could not find tenant id for provided tenant domain '<snip>'. Please ensure that the provided user is found in the provided tenant domain.

I encountered this error before and then I could fix it by running Clear-AzContext and then running Connect-AzAccount again. However when I run Clear-AzContext I now get the following error:

Clear-AzContext: Method not found: 'Microsoft.Identity.Client.PublicClientApplicationBuilder Microsoft.Identity.Client.Broker.BrokerExtension.WithBrokerPreview(Microsoft.Identity.Client.PublicClientApplicationBuilder, Boolean)'.

Outside of the Polyglot notebook I'm not experiencing any issues, both in the PowerShell terminal in VS Code and by running powershell directly from the start menu.

Issue script & Debug output

$DebugPreference='Continue'
Clear-AzContext -Force

DEBUG: 11:48:13 AM - ClearAzureRmContext begin processing with ParameterSet '__AllParameterSets'.
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 11:48:13 AM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 11:48:13 AM - No autosave setting detected in environment variable 'AzContextAutoSave'. 
DEBUG: 11:48:13 AM - Using Autosave scope 'CurrentUser'
DEBUG: 11:48:13 AM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 11:48:13 AM - No autosave setting detected in environment variable 'AzContextAutoSave'. 
DEBUG: 11:48:13 AM - Using Autosave scope 'CurrentUser'
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [DisableErrorRecordsPersistence], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
Clear-AzContext: 
Line |
   2 |  Clear-AzContext -Force
     |  ~~~~~~~~~~~~~~~~~~~~~~
     | Method not found: 'Microsoft.Identity.Client.PublicClientApplicationBuilder Microsoft.Identity.Client.Broker.BrokerExtension.WithBrokerPreview(Microsoft.Identity.Client.PublicClientApplicationBuilder, Boolean)'.
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 11:48:13 AM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: AzureQoSEvent:  Module: Az.Accounts:2.13.0; CommandName: Clear-AzContext; PSVersion: 7.3.6; IsSuccess: False; Duration: 00:00:00.0216796; Exception: Method not found: 'Microsoft.Identity.Client.PublicClientApplicationBuilder Microsoft.Identity.Client.Broker.BrokerExtension.WithBrokerPreview(Microsoft.Identity.Client.PublicClientApplicationBuilder, Boolean)'.;
DEBUG: 11:48:13 AM - ClearAzureRmContext end processing.

Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAccount -TenantId $AzureTenant -SubscriptionId $AzureSubscription
DEBUG: 12:06:30 PM - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'.
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 12:06:30 PM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 12:06:30 PM - No autosave setting detected in environment variable 'AzContextAutoSave'. 
DEBUG: 12:06:30 PM - Using Autosave scope 'CurrentUser'
DEBUG: 12:06:30 PM - Autosave setting from startup session: 'CurrentUser'
DEBUG: 12:06:30 PM - No autosave setting detected in environment variable 'AzContextAutoSave'. 
DEBUG: 12:06:30 PM - Using Autosave scope 'CurrentUser'
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [DisableErrorRecordsPersistence], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
Connect-AzAccount: 
Line |
   4 |  Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAcc …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Method not found: 'Void Azure.Core.TokenRequestContext..ctor(System.String[], System.String, System.String, System.String, Boolean)'.
Could not find tenant id for provided tenant domain '<snip>'. Please ensure that the provided user is found in the provided tenant domain.
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 12:06:30 PM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: AzureQoSEvent:  Module: Az.Accounts:2.13.0; CommandName: Connect-AzAccount; PSVersion: 7.3.6; IsSuccess: False; Duration: 00:00:00.0179444; Exception: Method not found: 'Void Azure.Core.TokenRequestContext..ctor(System.String[], System.String, System.String, System.String, Boolean)'.
Could not find tenant id for provided tenant domain '8<snip>'. Please ensure that the provided user is found in the provided tenant domain.;
DEBUG: 12:06:30 PM - ConnectAzureRmAccountCommand end processing.

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.6
PSEdition                      Core
GitCommitId                    7.3.6
OS                             Microsoft Windows 10.0.22621
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions

oduleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Script     10.3.0                AZ                                  
Script     2.13.0                Az.Accounts                         {Add-AzEnvironment, Clear-AzC…
Script     2.0.0                 Az.Advisor                          {Disable-AzAdvisorRecommendat…
Script     5.5.1                 Az.Aks                              {Disable-AzAksAddOn, Enable-A…
Script     1.1.4                 Az.AnalysisServices                 {Add-AzAnalysisServicesAccoun…
Script     4.0.2                 Az.ApiManagement                    {Add-AzApiManagementApiToGate…
Script     1.3.0                 Az.AppConfiguration                 {Clear-AzAppConfigurationDele…
Script     2.2.2                 Az.ApplicationInsights              {Get-AzApplicationInsights, G…
Script     1.0.0                 Az.ArcResourceBridge                {Get-AzArcResourceBridge, Get…
Script     2.0.0                 Az.Attestation                      {Add-AzAttestationPolicySigne…
Script     1.0.0                 Az.Automanage                       {Get-AzAutomanageBestPractice…
Script     1.9.1                 Az.Automation                       {Export-AzAutomationDscConfig…
Script     3.5.0                 Az.Batch                            {Disable-AzBatchAutoScale, Di…
Script     2.0.3                 Az.Billing                          {Get-AzBillingAccount, Get-Az…
Script     3.1.0                 Az.Cdn                              {Clear-AzCdnEndpointContent, …
Script     1.2.0                 Az.CloudService                     {Get-AzCloudService, Get-AzCl…
Script     1.14.0                Az.CognitiveServices                {Add-AzCognitiveServicesAccou…
Script     6.3.0                 Az.Compute                          {Add-AzImageDataDisk, Add-AzV…
Script     1.0.0                 Az.ConfidentialLedger               {Get-AzConfidentialLedger, Ne…
Script     3.2.1                 Az.ContainerInstance                {Add-AzContainerInstanceOutpu…
Script     4.1.1                 Az.ContainerRegistry                {Connect-AzContainerRegistry,…
Script     1.12.0                Az.CosmosDB                         {Get-AzCosmosDBAccount, Get-A…
Script     1.1.0                 Az.DataBoxEdge                      {Get-AzDataBoxEdgeBandwidthSc…
Script     1.7.0                 Az.Databricks                       {Get-AzDatabricksAccessConnec…
Script     1.17.0                Az.DataFactory                      {Add-AzDataFactoryV2DataFlowD…
Script     1.0.3                 Az.DataLakeAnalytics                {Add-AzDataLakeAnalyticsDataS…
Script     1.3.0                 Az.DataLakeStore                    {Add-AzDataLakeStoreFirewallR…
Script     2.0.0                 Az.DataProtection                   {Backup-AzDataProtectionBacku…
Script     1.0.1                 Az.DataShare                        {Get-AzDataShare, Get-AzDataS…
Script     1.1.0                 Az.DeploymentManager                {Get-AzDeploymentManagerArtif…
Script     4.0.0                 Az.DesktopVirtualization            {Disconnect-AzWvdUserSession,…
Script     1.0.2                 Az.DevTestLabs                      {Get-AzDtlAllowedVMSizesPolic…
Script     1.1.3                 Az.Dns                              {Add-AzDnsRecordConfig, Get-A…
Script     1.6.0                 Az.EventGrid                        {Enable-AzEventGridPartnerTop…
Script     4.1.0                 Az.EventHub                         {New-AzEventHubAuthorizationR…
Script     1.10.0                Az.FrontDoor                        {Disable-AzFrontDoorCustomDom…
Script     4.0.6                 Az.Functions                        {Get-AzFunctionApp, Get-AzFun…
Script     6.0.1                 Az.HDInsight                        {Add-AzHDInsightClusterIdenti…
Script     2.0.0                 Az.HealthcareApis                   {Get-AzHealthcareApisService,…
Script     2.7.5                 Az.IotHub                           {Add-AzIotHubCertificate, Add…
Script     4.11.0                Az.KeyVault                         {Add-AzKeyVaultCertificate, A…
Script     2.2.0                 Az.Kusto                            {Add-AzKustoClusterLanguageEx…
Script     1.0.0                 Az.LoadTesting                      {Get-AzLoad, New-AzLoad, Remo…
Script     1.5.0                 Az.LogicApp                         {Get-AzIntegrationAccount, Ge…
Script     1.1.3                 Az.MachineLearning                  {Add-AzMlWebServiceRegionalPr…
Script     1.0.0                 Az.MachineLearningServices          {Get-AzMLServiceQuota, Get-Az…
Script     1.3.1                 Az.Maintenance                      {Get-AzApplyUpdate, Get-AzCon…
Script     1.1.1                 Az.ManagedServiceIdentity           {Get-AzFederatedIdentityCrede…
Script     3.0.0                 Az.ManagedServices                  {Get-AzManagedServicesAssignm…
Script     2.0.0                 Az.MarketplaceOrdering              {Get-AzMarketplaceTerms, Invo…
Script     1.1.2                 Az.Media                            {Get-AzMediaService, Get-AzMe…
Script     2.2.0                 Az.Migrate                          {Get-AzMigrateDiscoveredServe…
Script     4.6.0                 Az.Monitor                          {Add-AzLogProfile, Add-AzMetr…
Script     1.1.1                 Az.MySql                            {Get-AzMySqlConfiguration, Ge…
Script     6.2.0                 Az.Network                          {Add-AzApplicationGatewayAuth…
Script     1.1.2                 Az.NotificationHubs                 {Get-AzNotificationHub, Get-A…
Script     3.2.0                 Az.OperationalInsights              {Disable-AzOperationalInsight…
Script     1.6.3                 Az.PolicyInsights                   {Get-AzPolicyAttestation, Get…
Script     1.1.0                 Az.PostgreSql                       {Get-AzPostgreSqlConfiguratio…
Script     1.2.1                 Az.PowerBIEmbedded                  {Get-AzPowerBIEmbeddedCapacit…
Script     1.0.4                 Az.PrivateDns                       {Add-AzPrivateDnsRecordConfig…
Script     6.5.1                 Az.RecoveryServices                 {Add-AzRecoveryServicesAsrRep…
Script     1.8.0                 Az.RedisCache                       {Export-AzRedisCache, Get-AzR…
Script     1.2.0                 Az.RedisEnterpriseCache             {Export-AzRedisEnterpriseCach…
Script     2.0.0                 Az.Relay                            {Get-AzRelayAuthorizationRule…
Script     1.1.0                 Az.ResourceMover                    {Add-AzResourceMoverMoveResou…
Script     6.10.0                Az.Resources                        {Export-AzResourceGroup, Expo…
Script     1.4.0                 Az.Security                         {Add-AzSecurityAdaptiveNetwor…
Script     3.0.2                 Az.SecurityInsights                 {Get-AzSentinelAlertRule, Get…
Script     3.0.0                 Az.ServiceBus                       {New-AzServiceBusAuthorizatio…
Script     3.2.0                 Az.ServiceFabric                    {Add-AzServiceFabricClientCer…
Script     2.0.0                 Az.SignalR                          {Get-AzSignalR, Get-AzSignalR…
Script     4.10.0                Az.Sql                              {Add-AzSqlDatabaseToFailoverG…
Script     2.1.0                 Az.SqlVirtualMachine                {Get-AzAvailabilityGroupListe…
Script     2.1.2                 Az.StackHCI                         {Add-AzStackHCIVMAttestation,…
Script     5.10.0                Az.Storage                          {Add-AzRmStorageContainerLega…
Script     1.0.1                 Az.StorageMover                     {Get-AzStorageMover, Get-AzSt…
Script     2.0.0                 Az.StorageSync                      {Get-AzStorageSyncCloudEndpoi…
Script     2.0.0                 Az.StreamAnalytics                  {Get-AzStreamAnalyticsCluster…
Script     1.0.0                 Az.Support                          {Get-AzSupportProblemClassifi…
Script     3.0.3                 Az.Synapse                          {Add-AzSynapseDataFlowDebugSe…
Script     1.2.1                 Az.TrafficManager                   {Add-AzTrafficManagerCustomHe…
Script     3.1.1                 Az.Websites                         {Add-AzWebAppAccessRestrictio…

Error output

Resolve-AzError -Last

Message        : Method not found: 'Microsoft.Identity.Client.PublicClientApplicationBuilder Micros
                 oft.Identity.Client.Broker.BrokerExtension.WithBrokerPreview(Microsoft.Identity.Cl
                 ient.PublicClientApplicationBuilder, Boolean)'.
StackTrace     :    at Microsoft.Azure.Commands.Common.Authentication.PowerShellTokenCacheProvider.
                 CreatePublicClient(String authority)
                    at Microsoft.Azure.Commands.Common.Authentication.SharedTokenCacheProvider.Clea
                 rCache()
                    at Microsoft.Azure.Commands.Profile.Context.ClearAzureRmContext.ClearContext(Az
                 ureRmProfile profile, RMProfileClient client)
                    at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.Modif
                 yContext(Action`2 contextAction)
                    at Microsoft.Azure.Commands.Profile.Context.ClearAzureRmContext.<ExecuteCmdlet>
                 b__9_0()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ConfirmAction
                 (Boolean force, String continueMessage, String processMessage, String target, 
                 Action action, Func`1 useShouldContinue)
                    at Microsoft.Azure.Commands.Profile.Context.ClearAzureRmContext.ExecuteCmdlet()
                    at 
                 Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : System.MissingMethodException
InvocationInfo : {Clear-AzContext}
Line           : Clear-AzContext -Force

Position       : At line:2 char:1
                 + Clear-AzContext -Force
                 + ~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 56

Message        : Method not found: 'Void Azure.Core.TokenRequestContext..ctor(System.String[], 
                 System.String, System.String, System.String, Boolean)'.
                 Could not find tenant id for provided tenant domain 
                 '<snip>'. Please ensure that the provided user is 
                 found in the provided tenant domain.
StackTrace     :    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzure
                 Account account, IAzureEnvironment environment, String tenantIdOrName, String 
                 subscriptionId, String subscriptionName, SecureString password, Boolean 
                 skipValidation, IOpenIDConfiguration openIDConfigDoc, Action`1 promptAction, 
                 String name, Boolean shouldPopulateContextList, Int32 maxContextPopulation, 
                 String authScope)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayCl
                 ass127_2.<ExecuteCmdlet>b__5()
                    at System.Threading.Tasks.Task`1.InnerInvoke()
                    at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread 
                 threadPoolThread, ExecutionContext executionContext, ContextCallback callback, 
                 Object state)
                 --- End of stack trace from previous location ---
                    at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread 
                 threadPoolThread, ExecutionContext executionContext, ContextCallback callback, 
                 Object state)
                    at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, 
                 Thread threadPoolThread)
                 --- End of stack trace from previous location ---
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayCl
                 ass127_1.<ExecuteCmdlet>b__1(AzureRmProfile localProfile, RMProfileClient 
                 profileClient, String name)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayCl
                 ass136_0.<SetContextWithOverwritePrompt>b__0(AzureRmProfile prof, RMProfileClient 
                 client)
                    at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.Modif
                 yContext(Action`2 contextAction)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWith
                 OverwritePrompt(Action`3 setContextAction)
                    at 
                 Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
                    at 
                 Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : System.ArgumentNullException
InvocationInfo : {Connect-AzAccount}
Line           : Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAccount 
                 -TenantId $AzureTenant -SubscriptionId $AzureSubscription
Position       : At line:4 char:1
                 + Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAcc …
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 58

Message        : Method not found: 'Void Azure.Core.TokenRequestContext..ctor(System.String[], 
                 System.String, System.String, System.String, Boolean)'.
StackTrace     :    at Microsoft.Azure.PowerShell.Authenticators.InteractiveUserAuthenticator.Authe
                 nticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
                    at Microsoft.Azure.Commands.Common.Authentication.DelegatingAuthenticator.TryAu
                 thenticate(AuthenticationParameters parameters, CancellationToken 
                 cancellationToken, Task`1& token)
                    at Microsoft.Azure.Commands.Common.Authentication.DelegatingAuthenticator.TryAu
                 thenticate(AuthenticationParameters parameters, Task`1& token)
                    at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFacto
                 ry.Authenticate(IAzureAccount account, IAzureEnvironment environment, String 
                 tenant, SecureString password, String promptBehavior, Action`1 promptAction, 
                 IAzureTokenCache tokenCache, String resourceId)
                    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAcces
                 sToken(IAzureAccount account, IAzureEnvironment environment, String tenantId, 
                 SecureString password, String promptBehavior, Action`1 promptAction, String 
                 resourceId)
                    at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzure
                 Account account, IAzureEnvironment environment, String tenantIdOrName, String 
                 subscriptionId, String subscriptionName, SecureString password, Boolean 
                 skipValidation, IOpenIDConfiguration openIDConfigDoc, Action`1 promptAction, 
                 String name, Boolean shouldPopulateContextList, Int32 maxContextPopulation, 
                 String authScope)
Exception      : System.MissingMethodException
InvocationInfo : {Connect-AzAccount}
Line           : Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAccount 
                 -TenantId $AzureTenant -SubscriptionId $AzureSubscription
Position       : At line:4 char:1
                 + Connect-AzAccount -Environment $AzureEnvironment -AccountId $AzureAcc …
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 58
MvanderBoom commented 1 year ago

The installed modules were screwy, did some clean up, rebooted and now it work.

a-stankevich commented 6 months ago

I'm having this issue to now after installing Microsoft.Graph. Can you possibly recall what steps did you make for cleanup?

MvanderBoom commented 6 months ago

I have several version of the Azure modules I believe, I cleaned those up to have only 1 version.