Azure / azure-powershell

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

Connect-AzAccount v2.1.2 errors with WriteObject and WriteError method error #13419

Closed mwsutherland closed 3 years ago

mwsutherland commented 3 years ago

Description

When calling Connect-AzAccount with no parameters, I get the following warning and error:

WARNING: Unable to acquire token for tenant 'organizations'
Connect-AzAccount : The WriteObject and WriteError methods cannot be called from outside the overrides of the
BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread.
Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer Support Services.
At line:1 char:1
+ Connect-AzAccount
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

If I revert back to Az.Accounts v1.9.5, it works.

Steps to reproduce

(Uninstall-Module for all Az.* modules/versions)

Install-Module Az -Scope AllUsers -AllowClobber
Connect-AzAccount

(get error)

In case it is relevant, without the -AllowClobber, I get the following error:

PackageManagement\Install-Package : The following commands are already available on this system:'Resolve-Error'. This
module 'Az.Accounts' may override the existing commands. If you still want to install this module 'Az.Accounts', use
-AllowClobber parameter.

Environment data

Name                           Value
----                           -----
PSVersion                      5.1.19041.546
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.546
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Module versions


    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Script     2.1.2      Az.Accounts                         {Disable-AzDataCollection, Disable-AzContextAutosave, Enab...
Script     1.1.1      Az.Advisor                          {Get-AzAdvisorRecommendation, Enable-AzAdvisorRecommendati...
Script     2.0.0      Az.Aks                              {Get-AzAksCluster, New-AzAksCluster, Remove-AzAksCluster, ...
Script     1.1.4      Az.AnalysisServices                 {Resume-AzAnalysisServicesServer, Suspend-AzAnalysisServic...
Script     2.1.0      Az.ApiManagement                    {Add-AzApiManagementApiToGateway, Add-AzApiManagementApiTo...
Script     1.1.0      Az.ApplicationInsights              {Get-AzApplicationInsights, New-AzApplicationInsights, Rem...
Script     1.4.0      Az.Automation                       {Get-AzAutomationHybridWorkerGroup, Remove-AzAutomationHyb...
Script     3.1.0      Az.Batch                            {Remove-AzBatchAccount, Get-AzBatchAccount, Get-AzBatchAcc...
Script     2.0.0      Az.Billing                          {Get-AzBillingInvoice, Get-AzBillingPeriod, Get-AzEnrollme...
Script     1.6.0      Az.Cdn                              {Get-AzCdnProfile, Get-AzCdnProfileSsoUrl, New-AzCdnProfil...
Script     1.8.0      Az.CognitiveServices                {Get-AzCognitiveServicesAccount, Get-AzCognitiveServicesAc...
Script     4.6.0      Az.Compute                          {Remove-AzAvailabilitySet, Get-AzAvailabilitySet, New-AzAv...
Script     1.0.3      Az.ContainerInstance                {New-AzContainerGroup, Get-AzContainerGroup, Remove-AzCont...
Script     2.0.0      Az.ContainerRegistry                {New-AzContainerRegistry, Get-AzContainerRegistry, Update-...
Script     1.1.0      Az.DataBoxEdge                      {Get-AzDataBoxEdgeJob, Get-AzDataBoxEdgeDevice, Invoke-AzD...
Script     1.0.1      Az.Databricks                       {Get-AzDatabricksVNetPeering, Get-AzDatabricksWorkspace, N...
Script     1.11.0     Az.DataFactory                      {Set-AzDataFactoryV2, Update-AzDataFactoryV2, Get-AzDataFa...
Script     1.0.2      Az.DataLakeAnalytics                {Get-AzDataLakeAnalyticsDataSource, New-AzDataLakeAnalytic...
Script     1.2.8      Az.DataLakeStore                    {Get-AzDataLakeStoreTrustedIdProvider, Remove-AzDataLakeSt...
Script     1.0.0      Az.DataShare                        {New-AzDataShareAccount, Get-AzDataShareAccount, Remove-Az...
Script     1.1.0      Az.DeploymentManager                {Get-AzDeploymentManagerArtifactSource, New-AzDeploymentMa...
Script     2.0.0      Az.DesktopVirtualization            {Disconnect-AzWvdUserSession, Get-AzWvdApplication, Get-Az...
Script     1.0.2      Az.DevTestLabs                      {Get-AzDtlAllowedVMSizesPolicy, Get-AzDtlAutoShutdownPolic...
Script     1.1.2      Az.Dns                              {Get-AzDnsRecordSet, New-AzDnsRecordConfig, Remove-AzDnsRe...
Script     1.3.0      Az.EventGrid                        {New-AzEventGridTopic, Get-AzEventGridTopic, Set-AzEventGr...
Script     1.7.0      Az.EventHub                         {New-AzEventHubNamespace, Get-AzEventHubNamespace, Set-AzE...
Script     1.6.1      Az.FrontDoor                        {New-AzFrontDoor, Get-AzFrontDoor, Set-AzFrontDoor, Remove...
Script     2.0.0      Az.Functions                        {Get-AzFunctionApp, Get-AzFunctionAppAvailableLocation, Ge...
Script     4.0.0      Az.HDInsight                        {Get-AzHDInsightJob, New-AzHDInsightSqoopJobDefinition, Wa...
Script     1.1.0      Az.HealthcareApis                   {New-AzHealthcareApisService, Remove-AzHealthcareApisServi...
Script     2.6.0      Az.IotHub                           {Add-AzIotHubKey, Get-AzIotHubEventHubConsumerGroup, Get-A...
Script     3.0.0      Az.KeyVault                         {Add-AzManagedHsmKey, Get-AzManagedHsmKey, Remove-AzManage...
Script     1.0.0      Az.Kusto                            {Add-AzKustoClusterLanguageExtension, Add-AzKustoDatabaseP...
Script     1.3.2      Az.LogicApp                         {Get-AzIntegrationAccountAgreement, Get-AzIntegrationAccou...
Script     1.1.3      Az.MachineLearning                  {Move-AzMlCommitmentAssociation, Get-AzMlCommitmentAssocia...
Script     1.1.0      Az.Maintenance                      {Get-AzApplyUpdate, Get-AzConfigurationAssignment, Get-AzM...
Script     2.0.0      Az.ManagedServices                  {Get-AzManagedServicesAssignment, New-AzManagedServicesAss...
Script     1.0.2      Az.MarketplaceOrdering              {Get-AzMarketplaceTerms, Set-AzMarketplaceTerms}             
Script     1.1.1      Az.Media                            {Sync-AzMediaServiceStorageKey, Set-AzMediaServiceKey, Get...
Script     2.2.0      Az.Monitor                          {Get-AzMetricDefinition, Get-AzMetric, Remove-AzLogProfile...
Script     4.1.0      Az.Network                          {Add-AzApplicationGatewayAuthenticationCertificate, Get-Az...
Script     1.1.1      Az.NotificationHubs                 {Get-AzNotificationHub, Get-AzNotificationHubAuthorization...
Script     2.3.0      Az.OperationalInsights              {New-AzOperationalInsightsAzureActivityLogDataSource, New-...
Script     1.3.1      Az.PolicyInsights                   {Get-AzPolicyEvent, Get-AzPolicyState, Get-AzPolicyStateSu...
Script     1.1.2      Az.PowerBIEmbedded                  {Remove-AzPowerBIWorkspaceCollection, Get-AzPowerBIWorkspa...
Script     1.0.3      Az.PrivateDns                       {Get-AzPrivateDnsZone, Remove-AzPrivateDnsZone, Set-AzPriv...
Script     3.0.0      Az.RecoveryServices                 {Get-AzRecoveryServicesBackupProperty, Get-AzRecoveryServi...
Script     1.4.0      Az.RedisCache                       {Remove-AzRedisCachePatchSchedule, New-AzRedisCacheSchedul...
Script     1.0.3      Az.Relay                            {New-AzRelayNamespace, Get-AzRelayNamespace, Set-AzRelayNa...
Script     3.0.0      Az.Resources                        {Get-AzProviderOperation, Remove-AzRoleAssignment, Get-AzR...
Script     1.4.1      Az.ServiceBus                       {New-AzServiceBusNamespace, Get-AzServiceBusNamespace, Set...
Script     2.2.0      Az.ServiceFabric                    {Add-AzServiceFabricClientCertificate, Add-AzServiceFabric...
Script     1.2.0      Az.SignalR                          {New-AzSignalR, Get-AzSignalR, Get-AzSignalRKey, New-AzSig...
Script     2.11.1     Az.Sql                              {Get-AzSqlDatabaseTransparentDataEncryption, Get-AzSqlData...
Script     1.1.0      Az.SqlVirtualMachine                {New-AzSqlVM, Get-AzSqlVM, Update-AzSqlVM, Remove-AzSqlVM...}
Script     3.0.0      Az.Storage                          {Get-AzStorageAccount, Get-AzStorageAccountKey, New-AzStor...
Script     1.3.0      Az.StorageSync                      {Invoke-AzStorageSyncCompatibilityCheck, New-AzStorageSync...
Script     1.0.1      Az.StreamAnalytics                  {Get-AzStreamAnalyticsFunction, Get-AzStreamAnalyticsDefau...
Script     1.0.0      Az.Support                          {Get-AzSupportService, Get-AzSupportProblemClassification,...
Script     1.0.4      Az.TrafficManager                   {Add-AzTrafficManagerCustomHeaderToEndpoint, Remove-AzTraf...
Script     2.0.0      Az.Websites                         {Get-AzAppServicePlan, Set-AzAppServicePlan, New-AzAppServ...
Binary     2.0.2.118  AzureAD                             {Add-AzureADApplicationOwner, Get-AzureADApplication, Get-...
Script     0.2.4.2    AzureAutomationAuthoringToolkit     {Get-AutomationVariable, Get-AutomationCertificate, Get-Au...
Script     1.0.128    dbatools                            {Select-DbaObject, Set-DbatoolsConfig, Start-DbaMigration,...
Script     0.2.0      DevOpsKitDsc                        {Initialize-DOKDsc, Import-DOKDscNodeConfiguration, Regist...
Script     2.1.0.1    EnhancedHTML2                       {ConvertTo-EnhancedHTML, ConvertTo-EnhancedHTMLFragment}     
Script     1.1.0.0    IISAdministration                                                                                
Script     1.0.1      Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}        
Script     1.4.7      PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Binary     1.0.0.1    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Script     5.0.4      Pester                              {Invoke-Pester, Describe, Context, It...}                    
Script     3.4.0      Pester                              {Describe, Context, It, Should...}                           
Script     1.3.6      PowerShellCookbook                  {Move-LockedFile, Invoke-ScriptBlock, Search-WmiNamespace,...
Script     2.2.5      PowerShellGet                       {Find-Command, Find-DSCResource, Find-Module, Find-RoleCap...
Script     1.0.0.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...} 
Script     0.3        PowerShellModule                                                                                 
Script     0.4.2      powershell-yaml                     {ConvertTo-Yaml, ConvertFrom-Yaml, cfy, cty}                 
Script     0.6.3      PSDocs                              {Document, Invoke-PSDocument, Get-PSDocumentHeader, New-PS...
Script     0.6.1      PSDocs.Dsc                          {Invoke-DscNodeDocument, Get-DscMofDocument}                 
Manifest   1.7.0.4    PSFTP                               {Add-FTPItem, Get-FTPChildItem, Get-FTPConnection, Get-FTP...
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remov...
Script     3.2.1      PSTeachingTools                     {Get-Vegetable, New-Vegetable, Set-Vegetable, Start-TypedD...
Script     21.1.18229 SqlServer                           {Add-RoleMember, Add-SqlAvailabilityDatabase, Add-SqlAvail...
Script     12.1.0.... VMware.CloudServices                {Connect-Vcs, Disconnect-Vcs, Get-VcsOrganizationRole, Get...
Script     7.0.0.1... VMware.DeployAutomation             {Add-DeployRule, Add-ProxyServer, Add-ScriptBundle, Copy-D...
Script     7.0.0.1... VMware.ImageBuilder                 {Add-EsxSoftwareDepot, Add-EsxSoftwarePackage, Compare-Esx...
Manifest   12.1.0.... VMware.PowerCLI                                                                                  
Script     7.0.1.1... VMware.Vim                                                                                       
Script     12.1.0.... VMware.VimAutomation.Cis.Core       {Connect-CisServer, Disconnect-CisServer, Get-CisService}    
Script     12.0.0.... VMware.VimAutomation.Cloud          {Add-CIDatastore, Connect-CIServer, Disconnect-CIServer, G...
Script     12.1.0.... VMware.VimAutomation.Common         {Get-Task, New-OAuthSecurityContext, Stop-Task, Wait-Task}   
Script     12.1.0.... VMware.VimAutomation.Core           {Add-PassthroughDevice, Add-VirtualSwitchPhysicalNetworkAd...
Script     12.1.0.... VMware.VimAutomation.Hcx            {Connect-HCXServer, Disconnect-HCXServer, Get-HCXAppliance...
Script     7.13.0.... VMware.VimAutomation.HorizonView    {Connect-HVServer, Disconnect-HVServer}                      
Script     12.0.0.... VMware.VimAutomation.License        Get-LicenseDataManager                                       
Script     12.0.0.... VMware.VimAutomation.Nsxt           {Connect-NsxtServer, Disconnect-NsxtServer, Get-NsxtPolicy...
Script     12.1.0.... VMware.VimAutomation.Sdk            Get-ErrorReport                                              
Script     12.1.0.... VMware.VimAutomation.Security       {Add-AttestationServiceInfo, Add-KeyProviderServiceInfo, A...
Script     12.1.0.... VMware.VimAutomation.Srm            {Connect-SrmServer, Disconnect-SrmServer}                    
Script     12.1.0.... VMware.VimAutomation.Storage        {Add-EntityDefaultKeyProvider, Add-KeyManagementServer, Ad...
Script     1.6.0.0    VMware.VimAutomation.StorageUtility Update-VmfsDatastore                                         
Script     12.1.0.... VMware.VimAutomation.Vds            {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, E...
Script     12.1.0.... VMware.VimAutomation.Vmc            {Add-VmcSddcHost, Connect-Vmc, Disconnect-Vmc, Get-AwsAcco...
Script     12.0.0.... VMware.VimAutomation.vROps          {Connect-OMServer, Disconnect-OMServer, Get-OMAlert, Get-O...
Script     12.1.0.... VMware.VimAutomation.WorkloadMan... {Disable-WMCluster, Enable-WMCluster, Get-WMCluster, Get-W...
Script     12.1.0.... VMware.VumAutomation                {Add-EntityBaseline, Copy-Patch, Get-Baseline, Get-Complia...

    Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Manifest   1.0.1.0    ActiveDirectory                     {Add-ADCentralAccessPolicyMember, Add-ADComputerServiceAcc...
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgro...
Manifest   2.0.0.0    AppLocker                           {Get-AppLockerFileInformation, Get-AppLockerPolicy, New-Ap...
Manifest   1.0.0.0    AppvClient                          {Add-AppvClientConnectionGroup, Add-AppvClientPackage, Add...
Manifest   2.0.1.0    Appx                                {Add-AppxPackage, Get-AppxPackage, Get-AppxPackageManifest...
Script     1.0.0.0    AssignedAccess                      {Clear-AssignedAccess, Get-AssignedAccess, Set-AssignedAcc...
Manifest   1.0        BestPractices                       {Get-BpaModel, Get-BpaResult, Invoke-BpaModel, Set-BpaResult}
Manifest   1.0.0.0    BitLocker                           {Unlock-BitLocker, Suspend-BitLocker, Resume-BitLocker, Re...
Manifest   2.0.0.0    BitsTransfer                        {Add-BitsFile, Complete-BitsTransfer, Get-BitsTransfer, Re...
Manifest   1.0.0.0    BranchCache                         {Add-BCDataCacheExtension, Clear-BCCache, Disable-BC, Disa...
Manifest   1.0.0.0    CimCmdlets                          {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance,...
Binary     2.0.0.0    ClusterAwareUpdating                {Get-CauPlugin, Register-CauPlugin, Unregister-CauPlugin, ...
Manifest   1.0        ConfigCI                            {Get-SystemDriver, New-CIPolicyRule, New-CIPolicy, Get-CIP...
Manifest   1.0        ConfigDefender                      {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest   1.0        Defender                            {Get-MpPreference, Set-MpPreference, Add-MpPreference, Rem...
Manifest   1.0.2.0    DeliveryOptimization                {Delete-DeliveryOptimizationCache, Set-DeliveryOptimizatio...
Manifest   1.0        DFSN                                {Get-DfsnRoot, Remove-DfsnRoot, Set-DfsnRoot, New-DfsnRoot...
Binary     2.0.0.0    DFSR                                {New-DfsReplicationGroup, Get-DfsReplicationGroup, Set-Dfs...
Manifest   2.0.0.0    DhcpServer                          {Add-DhcpServerInDC, Add-DhcpServerv4Class, Add-DhcpServer...
Manifest   1.0.0.0    DirectAccessClientComponents        {Disable-DAManualEntryPointSelection, Enable-DAManualEntry...
Script     3.0        Dism                                {Add-AppxProvisionedPackage, Add-WindowsDriver, Add-Window...
Manifest   1.0.0.0    DnsClient                           {Resolve-DnsName, Clear-DnsClientCache, Get-DnsClient, Get...
Manifest   2.0.0.0    DnsServer                           {Add-DnsServerConditionalForwarderZone, Add-DnsServerDirec...
Manifest   1.0.0.0    EventTracingManagement              {Start-EtwTraceSession, New-EtwTraceSession, Get-EtwTraceS...
Manifest   2.0.0.0    FailoverClusters                    {Add-ClusterCheckpoint, Add-ClusterDisk, Add-ClusterFileSe...
Manifest   1.0.0.0    GroupPolicy                         {Backup-GPO, Block-GPInheritance, Copy-GPO, Get-GPInherita...
Manifest   1.0.0.0    HgsClient                           {Get-HgsAttestationBaselinePolicy, Get-HgsClientConfigurat...
Manifest   1.0.0.0    HgsDiagnostics                      {New-HgsTraceTarget, Get-HgsTrace, Get-HgsTraceFileData, T...
Binary     1.0.0.0    HostComputeService                  {Get-ComputeProcess, Stop-ComputeProcess}                    
Manifest   1.0.0.1    HostNetworkingService               {Remove-HnsNamespace, Remove-HnsEndpoint, Get-HnsEndpoint,...
Binary     2.0.0.0    Hyper-V                             {Add-VMAssignableDevice, Add-VMDvdDrive, Add-VMFibreChanne...
Binary     1.1        Hyper-V                             {Add-VMDvdDrive, Add-VMFibreChannelHba, Add-VMHardDiskDriv...
Manifest   2.0.0.0    International                       {Get-WinDefaultInputMethodOverride, Set-WinDefaultInputMet...
Manifest   2.0.0.0    IpamServer                          {Get-IpamDhcpConfigurationEvent, Remove-IpamDhcpConfigurat...
Manifest   1.0.0.0    iSCSI                               {Get-IscsiTargetPortal, New-IscsiTargetPortal, Remove-Iscs...
Manifest   2.0.0.0    IscsiTarget                         {Add-ClusteriSCSITargetServerRole, Add-IscsiVirtualDiskTar...
Script     1.0.0.0    ISE                                 {New-IseSnippet, Import-IseSnippet, Get-IseSnippet}          
Manifest   1.0.0.0    Kds                                 {Add-KdsRootKey, Get-KdsRootKey, Test-KdsRootKey, Set-KdsC...
Manifest   1.0.1.0    Microsoft.PowerShell.Archive        {Compress-Archive, Expand-Archive}                           
Manifest   3.0.0.0    Microsoft.PowerShell.Diagnostics    {Get-WinEvent, Get-Counter, Import-Counter, Export-Counter...
Manifest   3.0.0.0    Microsoft.PowerShell.Host           {Start-Transcript, Stop-Transcript}                          
Manifest   1.0.0.0    Microsoft.PowerShell.LocalAccounts  {Add-LocalGroupMember, Disable-LocalUser, Enable-LocalUser...
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Content, Clear-Content, Clear-ItemProperty, Join-Path...
Script     1.0        Microsoft.PowerShell.ODataUtils     Export-ODataEndpointProxy                                    
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {Get-Acl, Set-Acl, Get-PfxCertificate, Get-Credential...}    
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Format-List, Format-Custom, Format-Table, Format-Wide...}   
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Disable-WSManCredSSP, Enable-WSManCredSSP, Get-WSManCredS...
Manifest   1.0        MMAgent                             {Disable-MMAgent, Enable-MMAgent, Set-MMAgent, Get-MMAgent...
Manifest   1.0.0.0    MsDtc                               {New-DtcDiagnosticTransaction, Complete-DtcDiagnosticTrans...
Manifest   2.0.0.0    NetAdapter                          {Disable-NetAdapter, Disable-NetAdapterBinding, Disable-Ne...
Manifest   1.0.0.0    NetConnection                       {Get-NetConnectionProfile, Set-NetConnectionProfile}         
Manifest   1.0.0.0    NetDiagnostics                      Get-NetView                                                  
Manifest   1.0.0.0    NetEventPacketCapture               {New-NetEventSession, Remove-NetEventSession, Get-NetEvent...
Manifest   2.0.0.0    NetLbfo                             {Add-NetLbfoTeamMember, Add-NetLbfoTeamNic, Get-NetLbfoTea...
Manifest   1.0        NetLldpAgent                        {Enable-NetLldpAgent, Disable-NetLldpAgent, Get-NetLldpAgent}
Manifest   1.0.0.0    NetNat                              {Get-NetNat, Get-NetNatExternalAddress, Get-NetNatStaticMa...
Manifest   2.0.0.0    NetQos                              {Get-NetQosPolicy, Set-NetQosPolicy, Remove-NetQosPolicy, ...
Manifest   2.0.0.0    NetSecurity                         {Get-DAPolicyChange, New-NetIPsecAuthProposal, New-NetIPse...
Manifest   1.0.0.0    NetSwitchTeam                       {New-NetSwitchTeam, Remove-NetSwitchTeam, Get-NetSwitchTea...
Manifest   1.0.0.0    NetTCPIP                            {Get-NetIPAddress, Get-NetIPInterface, Get-NetIPv4Protocol...
Manifest   1.0.0.0    NetworkConnectivityStatus           {Get-DAConnectionStatus, Get-NCSIPolicyConfiguration, Rese...
Manifest   1.0.0.0    NetworkController                   {Add-NetworkControllerNode, Disable-NetworkControllerNode,...
Manifest   1.0.0.0    NetworkControllerDiagnostics        {Get-NetworkControllerDeploymentInfo, Get-NetworkControlle...
Manifest   2.0.0.0    NetworkLoadBalancingClusters        {Add-NlbClusterNode, Add-NlbClusterNodeDip, Add-NlbCluster...
Manifest   1.0.0.0    NetworkSwitchManager                {Disable-NetworkSwitchEthernetPort, Enable-NetworkSwitchEt...
Manifest   1.0.0.0    NetworkTransition                   {Add-NetIPHttpsCertBinding, Disable-NetDnsTransitionConfig...
Manifest   1.0        NFS                                 {Get-NfsMappedIdentity, Get-NfsNetgroup, Install-NfsMappin...
Manifest   1.0.0.0    PcsvDevice                          {Get-PcsvDevice, Start-PcsvDevice, Stop-PcsvDevice, Restar...
Binary     1.0.0.0    PersistentMemory                    {Get-PmemDisk, Get-PmemPhysicalDevice, Get-PmemUnusedRegio...
Manifest   1.0.0.0    PKI                                 {Add-CertificateEnrollmentPolicyServer, Export-Certificate...
Manifest   1.0.0.0    PnpDevice                           {Get-PnpDevice, Get-PnpDeviceProperty, Enable-PnpDevice, D...
Manifest   1.1        PrintManagement                     {Add-Printer, Add-PrinterDriver, Add-PrinterPort, Get-Prin...
Binary     1.0.11     ProcessMitigations                  {Get-ProcessMitigation, Set-ProcessMitigation, ConvertTo-P...
Script     3.0        Provisioning                        {Install-ProvisioningPackage, Export-ProvisioningPackage, ...
Manifest   1.1        PSDesiredStateConfiguration         {Set-DscLocalConfigurationManager, Start-DscConfiguration,...
Script     1.0.0.0    PSDiagnostics                       {Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WS...
Binary     1.1.0.0    PSScheduledJob                      {New-JobTrigger, Add-JobTrigger, Remove-JobTrigger, Get-Jo...
Manifest   2.0.0.0    PSWorkflow                          {New-PSWorkflowExecutionOption, New-PSWorkflowSession, nwsn} 
Manifest   1.0.0.0    PSWorkflowUtility                   Invoke-AsWorkflow                                            
Manifest   3.0.0.0    RemoteAccess                        {Add-DAAppServer, Add-DAClient, Add-DAClientDnsConfigurati...
Manifest   2.0.0.0    RemoteDesktop                       {Get-RDCertificate, Set-RDCertificate, New-RDCertificate, ...
Manifest   1.0.0.0    ScheduledTasks                      {Get-ScheduledTask, Set-ScheduledTask, Register-ScheduledT...
Manifest   2.0.0.0    SecureBoot                          {Confirm-SecureBootUEFI, Set-SecureBootUEFI, Get-SecureBoo...
Script     2.0.0.0    ServerManager                       {Get-WindowsFeature, Install-WindowsFeature, Uninstall-Win...
Cim        1.0.0.0    ServerManagerTasks                  {Get-SMCounterSample, Get-SMPerformanceCollector, Start-SM...
Manifest   1.0.0.0    ShieldedVMDataFile                  {Import-ShieldingDataFile, New-ShieldingDataFile, New-Volu...
Manifest   1.0.0.0    ShieldedVMTemplate                  {Protect-TemplateDisk, Initialize-VMShieldingHelperVHD}      
Manifest   2.0.0.0    SmbShare                            {Get-SmbShare, Remove-SmbShare, Set-SmbShare, Block-SmbSha...
Manifest   2.0.0.0    SmbWitness                          {Get-SmbWitnessClient, Move-SmbWitnessClient, gsmbw, msmbw...
Manifest   1.0.0.0    StartLayout                         {Export-StartLayout, Import-StartLayout, Export-StartLayou...
Manifest   2.0.0.0    Storage                             {Add-InitiatorIdToMaskingSet, Add-PartitionAccessPath, Add...
Manifest   1.0.0.0    StorageBusCache                     {Clear-StorageBusDisk, Disable-StorageBusCache, Disable-St...
Binary     1.0.0.0    StorageMigrationService             {Get-SmsInventory, New-SmsInventory, Remove-SmsInventory, ...
Manifest   1.0.0.0    StorageQoS                          {Get-StorageQoSPolicy, Get-StorageQoSPolicyStore, Set-Stor...
Manifest   1.0        StorageReplica                      {Test-SRTopology, New-SRGroup, Remove-SRGroup, Set-SRGroup...
Binary     1.0.0.0    SystemInsights                      {Add-InsightsCapability, Remove-InsightsCapability, Update...
Manifest   2.0.0.0    TLS                                 {New-TlsSessionTicketKey, Enable-TlsSessionTicketKey, Disa...
Manifest   1.0.0.0    TroubleshootingPack                 {Get-TroubleshootingPack, Invoke-TroubleshootingPack}        
Manifest   2.0.0.0    TrustedPlatformModule               {Get-Tpm, Initialize-Tpm, Clear-Tpm, Unblock-Tpm...}         
Binary     2.1.639.0  UEV                                 {Clear-UevConfiguration, Clear-UevAppxPackage, Restore-Uev...
Manifest   2.0.0.0    UpdateServices                      {Add-WsusComputer, Approve-WsusUpdate, Deny-WsusUpdate, Ge...
Manifest   2.0.0.0    VpnClient                           {Add-VpnConnection, Set-VpnConnection, Remove-VpnConnectio...
Manifest   1.0.0.0    Wdac                                {Get-OdbcDriver, Set-OdbcDriver, Get-OdbcDsn, Add-OdbcDsn...}
Manifest   2.0.0.0    Whea                                {Get-WheaMemoryPolicy, Set-WheaMemoryPolicy}                 
Manifest   1.0.0.0    WindowsDeveloperLicense             {Get-WindowsDeveloperLicense, Unregister-WindowsDeveloperL...
Script     1.0        WindowsErrorReporting               {Enable-WindowsErrorReporting, Disable-WindowsErrorReporti...
Manifest   1.0.0.0    WindowsSearch                       {Get-WindowsSearchSetting, Set-WindowsSearchSetting}         
Manifest   1.0.0.0    WindowsUpdate                       Get-WindowsUpdateLog                                         
Manifest   1.0.0.2    WindowsUpdateProvider               {Get-WUAVersion, Get-WULastInstallationDate, Get-WULastSca...

    Directory: C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Manifest   1.0        SQLASCMDLETS                        {Add-RoleMember, Backup-ASDatabase, Invoke-ASCmd, Invoke-P...
Manifest   1.0        SQLPS                               {Backup-SqlDatabase, Add-SqlAvailabilityDatabase, Disable-...

    Directory: C:\tools\powershell\modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Script     1.0.2      IEICredsUtils                       {Get-UserFullName, Get-SavedUserCreds, New-SavedUserCreds,...
Script     1.0.0      IEICredsUtils                       {Get-UserFullName, Get-SavedUserCreds, New-SavedUserCreds,...

    Directory: C:\Program Files (x86)\Microsoft SQL Server\150\Tools\PowerShell\Modules

ModuleType Version    Name                                ExportedCommands                                             
---------- -------    ----                                ----------------                                             
Manifest   15.0       SQLPS                               {Backup-SqlDatabase, Save-SqlMigrationReport, Invoke-Polic...

Debug output

WARNING: Unable to acquire token for tenant 'organizations'
Connect-AzAccount : The WriteObject and WriteError methods cannot be called from outside the overrides of the
BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within the same thread.
Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer Support Services.
At line:1 char:1
+ Connect-AzAccount
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

Error output

   HistoryId: 14

Message        : The WriteObject and WriteError methods cannot be called from outside the overrides of the
                 BeginProcessing, ProcessRecord, and EndProcessing methods, and they can only be called from within
                 the same thread. Validate that the cmdlet makes these calls correctly, or contact Microsoft Customer
                 Support Services.
StackTrace     :    at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzu
                 reAccount account, IAzureEnvironment environment, String tenant, SecureString password, String
                 promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
                    at
                 Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount
                 account, IAzureEnvironment environment, String tenantId, SecureString password, String
                 promptBehavior, Action`1 promptAction)
                    at
                 Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount
                 account, IAzureEnvironment environment, SecureString password, String promptBehavior, Action`1
                 promptAction)
                    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)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass106_1.<ExecuteCmd
                 let>b__3()
                    at System.Threading.Tasks.Task`1.InnerInvoke()
                    at System.Threading.Tasks.Task.Execute()
                 --- End of stack trace from previous location where exception was thrown ---
                    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass106_0.<ExecuteCmd
                 let>b__0(AzureRmProfile localProfile, RMProfileClient profileClient, String name)
                    at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2
                 contextAction)
                    at
                 Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3
                 setContextAction)
                    at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : System.Management.Automation.PSInvalidOperationException
InvocationInfo : {Connect-AzAccount}
Line           : Connect-AzAccount
Position       : At line:1 char:1
                 + Connect-AzAccount
                 + ~~~~~~~~~~~~~~~~~
HistoryId      : 14
dingmeng-xue commented 3 years ago

@erich-wang , please look into this question.

erich-wang commented 3 years ago

@mwsutherland, I've just made some change in this branch and generated one preview version of Az.Accounts. However I could not verify the fix because I could not reproduce the issue.

Could you please help to verify whether the issue be fixed in preview bits by following below steps?

  1. Close all Windows PowerShell windows and start new one
  2. Download Az.Accounts 2.1.3 preview bits from here and save to your local disk, e.g. d:\az
  3. Register repository and install Az.Accounts:
    Register-PSRepository -Name temp -SourceLocation d:\az -InstallationPolicy Trusted
    Install-Module Az.Accounts -Repository temp -Force -SkipPublisherCheck
  4. Enable debug stream and login, please share the output if the issue remains
    $DebugPreference='Continue'
    Connect-AzAccounts
  5. Cleanup: restart Window PowerShell and uninstall Az.Accounts
    Uninstall-Module Az.Accounts
    Unregister-PSRepository -Name temp
valaman commented 3 years ago

I was running into the same issue, your fix is working, thank you!

erich-wang commented 3 years ago

@valaman , thank you very much for the help. The official version should be Az.Accounts 2.2.0 and will be released around Nov 17, thanks.

mwsutherland commented 3 years ago

It worked for me, too. Thanks!

erich-wang commented 3 years ago

@mwsutherland , thank you for the confirmation.

mcurko commented 3 years ago

I've had a similar problem with Login-AzAccount, and your module version solved it. Is the fact that I had to use -AllowClobber to install it important? (old Az.Accounts was uninstalled beforehand)

Correction: it's not solved, it worked once, and when I closed and reoped PS a got:

PS C:\WINDOWS\system32> Login-AzAccount
DEBUG: 7:56:54 - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'.
DEBUG: ExecuteCmdlet:1 thread id: 10
DEBUG: 7:56:54 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 7:56:54 - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 7:56:54 - Using Autosave scope 'CurrentUser'
Login-AzAccount : The default context can no longer be found; please run 'Get-AzContext -ListAvailable' to see all avai
lable contexts, 'Select-AzContext' to select a new default context, or 'Connect-AzAccount' to login with a new account.
At line:1 char:1
+ Login-AzAccount
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

DEBUG: AzureQoSEvent: CommandName - Connect-AzAccount; IsSuccess - False; Duration - 00:00:00.0308815;; Exception -
System.Management.Automation.PSInvalidOperationException: The default context can no longer be found; please run
'Get-AzContext -ListAvailable' to see all available contexts, 'Select-AzContext' to select a new default context, or
'Connect-AzAccount' to login with a new account.
   at Microsoft.Azure.Commands.Common.Authentication.Models.AzureRmProfile.get_DefaultContext()
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient..ctor(IProfileOperations profile)
   at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
   at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3
setContextAction)
   at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 7:56:55 - ConnectAzureRmAccountCommand end processing.
mcurko commented 3 years ago

And then, after deleting Az contet jsons in user folder:

PS C:\Windows\System32\WindowsPowerShell\v1.0> Login-AzAccount
WARNING: Unable to acquire token for tenant '************'
WARNING: Unable to acquire token for tenant 'organizations'
Login-AzAccount : One or more errors occurred.
At line:1 char:1
+ Login-AzAccount
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], AggregateException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
mcurko commented 3 years ago
PS C:\Windows\System32\WindowsPowerShell\v1.0> Login-AzAccount
DEBUG: 8:03:14 - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'.
DEBUG: ExecuteCmdlet:1 thread id: 10
DEBUG: 8:03:14 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 8:03:14 - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 8:03:14 - Using Autosave scope 'CurrentUser'
DEBUG: ExecuteCmdlet:2 thread id: 10
DEBUG: InteractiveBrowserCredential.Authenticate invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: Request [6feb4a42-e835-470b-9a38-1f8932336639] POST
https://login.microsoftonline.com/organizations/oauth2/v2.0/token
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
x-client-current-telemetry:REDACTED
x-client-last-telemetry:REDACTED
x-ms-PKeyAuth:REDACTED
x-ms-lib-capability:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
x-ms-client-request-id:6feb4a42-e835-470b-9a38-1f8932336639
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.4.0-beta.1 (.NET Framework 4.8.4250.0; Microsoft Windows 10.0.18363 )
client assembly: Azure.Identity
DEBUG: Response [6feb4a42-e835-470b-9a38-1f8932336639] 200 OK (00.5s)
Pragma:no-cache
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
client-request-id:REDACTED
x-ms-request-id:REDACTED
x-ms-ests-server:REDACTED
x-ms-clitelem:REDACTED
Cache-Control:no-store, no-cache
Content-Type:application/json; charset=utf-8
Expires:-1
P3P:REDACTED
Set-Cookie:REDACTED
Date:Fri, 13 Nov 2020 07:03:17 GMT
Content-Length:4842
DEBUG: InteractiveBrowserCredential.Authenticate succeeded. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:  ExpiresOn: 2020-11-13T08:03:17.0000000+00:00
DEBUG: InteractiveBrowserCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: InteractiveBrowserCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:  ExpiresOn: 2020-11-13T08:03:17.0000000+00:00
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/tenants?api-version=2019-06-01

Headers:
x-ms-client-request-id        : c84eb1b3-65e4-4ced-80a9-124bfa9ad1e7
accept-language               : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-tenant-reads: 11999
x-ms-request-id               : 187c161a-bd98-40af-b5cc-9eecafafb5fe
x-ms-correlation-request-id   : 187c161a-bd98-40af-b5cc-9eecafafb5fe
x-ms-routing-request-id       : SWITZERLANDNORTH:20201113T070318Z:187c161a-bd98-40af-b5cc-9eecafafb5fe
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Fri, 13 Nov 2020 07:03:18 GMT

Body:
{
  "value": [
    {
      "id": "/tenants/<Subscription ID>",
      "tenantId": "<Subscription ID>",
      "countryCode": "HR",
      "displayName": "Default Directory",
      "domains": [
        "<REDACTED>",
        "<REDACTED>",
        "<REDACTED>"
      ],
      "tenantCategory": "Home"
    }
  ]
}

DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [
https://management.core.windows.net//.default ] ParentRequestId:  Exception:
Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No
account matching the specified username: <my-email> tenantId: <Subscription ID> was found
in the cache.
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [
https://management.core.windows.net//.default ] ParentRequestId:  Exception:
Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No
account matching the specified username: <my-email> tenantId: <Subscription ID> was found
in the cache.
WARNING: Unable to acquire token for tenant '<Subscription ID>'
DEBUG: ExecuteCmdlet:3 thread id: 10

DEBUG: AzureQoSEvent: CommandName - Connect-AzAccount; IsSuccess - True; Duration - 00:00:04.6634972;
DEBUG: Finish sending metric.
DEBUG: 8:03:19 - ConnectAzureRmAccountCommand end processing.
Account              SubscriptionName TenantId Environment
-------              ---------------- -------- -----------
<my-email>                           AzureCloud

PS C:\Windows\System32\WindowsPowerShell\v1.0> Set-AzContext -SubscriptionId f85f6015-01ca-4470-b4d8-c0e0ee95c121
DEBUG: 8:05:38 - SetAzureRMContextCommand begin processing with ParameterSet 'Subscription'.
DEBUG: 8:05:38 - using account id '<my-email>'...
DEBUG: 8:05:38 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 8:05:38 - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 8:05:38 - Using Autosave scope 'CurrentUser'
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [
https://management.core.windows.net//.default ] ParentRequestId:  Exception:
Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No
account matching the specified username: <my-email> was found in the cache.
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ]
ParentRequestId:
DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [
https://management.core.windows.net//.default ] ParentRequestId:  Exception:
Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No
account matching the specified username: <my-email> was found in the cache.
WARNING: Unable to acquire token for tenant 'organizations'
Set-AzContext : SharedTokenCacheCredential authentication unavailable. No account matching the specified username: mark
ocurko@yahoo.com was found in the cache.
At line:1 char:1
+ Set-AzContext -SubscriptionId f85f6015-01ca-4470-b4d8-c0e0ee95c121
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Set-AzContext], CredentialUnavailableException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand

DEBUG: AzureQoSEvent: CommandName - Set-AzContext; IsSuccess - False; Duration - 00:00:00.1071598;; Exception -
Azure.Identity.CredentialUnavailableException: SharedTokenCacheCredential authentication unavailable. No account
matching the specified username: <my-email> was found in the cache.
   at Azure.Identity.SharedTokenCacheCredential.<GetAccountAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Azure.Identity.SharedTokenCacheCredential.<GetTokenImplAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex)
   at Azure.Identity.SharedTokenCacheCredential.<GetTokenImplAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Azure.Identity.SharedTokenCacheCredential.<GetTokenAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.PowerShell.Authenticators.MsalAccessToken.<GetAccessTokenAsync>d__33.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   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)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount account,
IAzureEnvironment environment, String tenantId, SecureString password, String promptBehavior, Action`1 promptAction)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount account,
IAzureEnvironment environment, SecureString password, String promptBehavior, Action`1 promptAction)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListTenants(String tenant)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListSubscriptions(String tenantIdOrDomain)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.TryGetSubscriptionById(String tenantId, String
subscriptionId, IAzureSubscription& subscription)
   at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.SetCurrentContext(String subscriptionNameOrId,
String tenantId, String name)
   at
Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand.<>c__DisplayClass37_0.<ExecuteCmdlet>b__2(AzureRmProfile
profile, RMProfileClient client, String name)
   at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
   at Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand.SetContextWithOverwritePrompt(Action`3
setContextAction)
   at Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand.ExecuteCmdlet()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 8:05:40 - SetAzureRMContextCommand end processing.
mcurko commented 3 years ago

I uninstalled all the Azure AzureRm Az modules, reinstalled Az modules, the module you made available, and tried again. I seem to connect with Connect-AzAccount -Tenant '...' -SubscriptionId '.........', but next command fails immediately:

`PS C:\Users\mcurko> Connect-AzAccount -Tenant '' -SubscriptionId '' DEBUG: 11:05:51 - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'. DEBUG: 11:05:51 - Autosave setting from startup session: 'CurrentUser' DEBUG: 11:05:51 - No autosave setting detected in environment variable 'AzContextAutoSave'. DEBUG: 11:05:51 - Using Autosave scope 'CurrentUser' DEBUG: InteractiveBrowserCredential.Authenticate invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: DEBUG: Request [64115148-8d86-45e5-abe7-6127335eaf5f] POST https://login.microsoftonline.com//oauth2/v2.0/token x-client-SKU:REDACTED x-client-Ver:REDACTED x-client-OS:REDACTED x-client-current-telemetry:REDACTED x-client-last-telemetry:REDACTED x-ms-PKeyAuth:REDACTED x-ms-lib-capability:REDACTED client-request-id:REDACTED return-client-request-id:REDACTED x-app-name:REDACTED x-app-ver:REDACTED x-ms-client-request-id:64115148-8d86-45e5-abe7-6127335eaf5f x-ms-return-client-request-id:true User-Agent:azsdk-net-Identity/1.4.0-beta.1,(.NET 5.0.0; Microsoft Windows 10.0.18363) client assembly: Azure.Identity DEBUG: Response [64115148-8d86-45e5-abe7-6127335eaf5f] 200 OK (00.9s) Cache-Control:no-store, no-cache Pragma:no-cache Strict-Transport-Security:REDACTED X-Content-Type-Options:REDACTED P3P:REDACTED client-request-id:REDACTED x-ms-request-id:REDACTED x-ms-ests-server:REDACTED x-ms-clitelem:REDACTED Set-Cookie:REDACTED Date:Fri, 13 Nov 2020 10:05:56 GMT Content-Type:application/json; charset=utf-8 Expires:-1 Content-Length:5628

DEBUG: InteractiveBrowserCredential.Authenticate succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: ExpiresOn: 2020-11-13T11:05:54.0000000+00:00 DEBUG: InteractiveBrowserCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: DEBUG: InteractiveBrowserCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: ExpiresOn: 2020-11-13T11:05:54.0000000+00:00 DEBUG: ============================ HTTP REQUEST ============================

HTTP Method: GET

Absolute Uri: https://management.azure.com/subscriptions/?api-version=2019-06-01

Headers: x-ms-client-request-id : 8830e9b7-b583-4977-8907-c8f8054a88a9 Accept-Language : en-US

Body:

DEBUG: ============================ HTTP RESPONSE ============================

Status Code: OK

Headers: Cache-Control : no-cache Pragma : no-cache x-ms-ratelimit-remaining-subscription-reads: 11992 x-ms-request-id : 878cafe4-fe90-466e-bea6-22c81933e4ba x-ms-correlation-request-id : 878cafe4-fe90-466e-bea6-22c81933e4ba x-ms-routing-request-id : SWITZERLANDNORTH:20201113T100557Z:878cafe4-fe90-466e-bea6-22c81933e4ba Strict-Transport-Security : max-age=31536000; includeSubDomains X-Content-Type-Options : nosniff Date : Fri, 13 Nov 2020 10:05:57 GMT

Body: { "id": "/subscriptions/", "authorizationSource": "Legacy", "managedByTenants": [ { "tenantId": "2f4a9838-26b7-47ee-be60-ccc1fdec5953" } ], "subscriptionId": "", "tenantId": "", "displayName": "Visual Studio Enterprise with MSDN", "state": "Enabled", "subscriptionPolicies": { "locationPlacementId": "Public_2014-09-01", "quotaId": "MSDN_2014-09-01", "spendingLimit": "On" } }

DEBUG: AzureQoSEvent: CommandName - Connect-AzAccount; IsSuccess - True; Duration - 00:00:04.4417275; DEBUG: Finish sending metric. DEBUG: 11:05:56 - ConnectAzureRmAccountCommand end processing. Account SubscriptionName TenantId Environment


Visual Studio Enterprise with MSDN AzureCloud PS C:\Users\mcurko> $resourceGroup = "myResourceGroup" PS C:\Users\mcurko> $location = "EastUS2" PS C:\Users\mcurko> PS C:\Users\mcurko> New-AzResourceGroup -Name $resourceGroup -Location $location DEBUG: 11:06:03 - NewAzureResourceGroupCmdlet begin processing with ParameterSet '__AllParameterSets'. DEBUG: 11:06:03 - using account id ''... DEBUG: [Common.Authentication]: Authenticating using Account: '', environment: 'AzureCloud', tenant: '' DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: Exception: Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No account matching the specified username: tenantId: was found in the cache. DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: DEBUG: SharedTokenCacheCredential.GetToken was unable to retrieve an access token. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: Exception: Azure.Identity.CredentialUnavailableException (0x80131500): SharedTokenCacheCredential authentication unavailable. No account matching the specified username: tenantId: was found in the cache. DEBUG: [Common.Authentication]: Received exception SharedTokenCacheCredential authentication unavailable. No account matching the specified username: tenantId: was found in the cache., while authenticating. New-AzResourceGroup: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials. DEBUG: AzureQoSEvent: CommandName - New-AzResourceGroup; IsSuccess - False; Duration - 00:00:00.0675654;; Exception - System.ArgumentException: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials. ---> Azure.Identity.CredentialUnavailableException: SharedTokenCacheCredential authentication unavailable. No account matching the specified username: tenantId: was found in the cache. 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) at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzureAccount account, IAzureEnvironment environment, String tenant, SecureString password, String promptBehavior, Action`1 promptAction, String resourceId) at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.GetServiceClientCredentials(IAzureContext context, String targetEndpoint) --- End of inner exception stack trace --- at Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.ResourceManagerCmdletBase.HandleException(ExceptionDispatchInfo capturedException) at Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.ResourceManagerCmdletBase.ExecuteCmdlet() at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.b__3_0(T c) at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor) at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet) at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord(); DEBUG: Finish sending metric. DEBUG: 11:06:04 - NewAzureResourceGroupCmdlet end processing.`
erich-wang commented 3 years ago

@mcurko, this seems a different issue, could you please file new file and provide detail info as described in bug template?

erich-wang commented 3 years ago

Close the issue as it has been addressed in Az.Accounts 2.2 which will be released on Nov 17.