Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.25k stars 3.85k forks source link

No default context and cannot select a new one #13359

Closed samme78 closed 3 years ago

samme78 commented 4 years ago

Description

I cannot connect to my azure account with the 'Connect-AzAccount' command. I get an error message saying the default context cannot be found. Basically all AZ commands return the same error message.

Steps to reproduce

I do not remember the exact steps I took to end up in this state but they were similar to this:

  1. I connected to an AZ account I have not used before (in the same directory as the old one) and tried to deploy some arm templates to azure via a PowerShell script.
  2. The script failed on the first command 'Get-AzADGroup'
  3. I though the error was related to not having a subscription or context set so I tried to set it but it did not work. (I don't remember the exact error or steps I took here)
  4. I realized there were a new version of azure-powershell so I installed the new version by following the steps on https://docs.microsoft.com/en-us/powershell/azure/install-az-ps?view=azps-5.0.0. I did not uninstall the old version before running the install.
  5. I can no longer run Connect-AzAccount

The two context visible below are tied to the old account.

Connect-AzAccount
Get-AzContext -ListAvailable
Select-AzContext "Visual Studio Professional (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) - xx@xx.se"

Environment data

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

Module versions

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     2.1.0      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...
Script     1.0.1      Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation}
Binary     1.0.0.1    PackageManagement                   {Find-Package, Get-Package, Get-PackageProvider, Get-Packa...
Script     3.4.0      Pester                              {Describe, Context, It, Should...}
Script     1.0.0.1    PowerShellGet                       {Install-Module, Find-Module, Save-Module, Update-Module...}
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Set-PSReadLineKeyHandler, Remov...
Script     21.1.18228 SqlServer                           {Add-RoleMember, Add-SqlAvailabilityDatabase, Add-SqlAvail...

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

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
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.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,...
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, Get-DeliveryOptimizatio...
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   1.0.0.0    EventTracingManagement              {Start-EtwTraceSession, New-EtwTraceSession, Get-EtwTraceS...
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...
Script     1.1.0.0    IISAdministration                   {Get-IISAppPool, Start-IISCommitDelay, Stop-IISCommitDelay...
Manifest   2.0.0.0    International                       {Get-WinDefaultInputMethodOverride, Set-WinDefaultInputMet...
Manifest   1.0.0.0    iSCSI                               {Get-IscsiTargetPortal, New-IscsiTargetPortal, Remove-Iscs...
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.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    NetworkSwitchManager                {Disable-NetworkSwitchEthernetPort, Enable-NetworkSwitchEt...
Manifest   1.0.0.0    NetworkTransition                   {Add-NetIPHttpsCertBinding, Disable-NetDnsTransitionConfig...
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   1.0.0.0    ScheduledTasks                      {Get-ScheduledTask, Set-ScheduledTask, Register-ScheduledT...
Manifest   2.0.0.0    SecureBoot                          {Confirm-SecureBootUEFI, Set-SecureBootUEFI, Get-SecureBoo...
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...
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   1.0.0.0    Wdac                                {Get-OdbcDriver, Set-OdbcDriver, Get-OdbcDsn, Add-OdbcDsn...}
Manifest   1.0.0.0    WebAdministration                   {Start-WebCommitDelay, Stop-WebCommitDelay, Get-WebConfigu...
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...
Manifest   2.0.0.0    VpnClient                           {Add-VpnConnection, Set-VpnConnection, Remove-VpnConnectio...

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

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0        SQLPS                               {Backup-SqlDatabase, Save-SqlMigrationReport, Add-SqlAvail...

Debug output

PS C:\WINDOWS\system32> Connect-AzAccount
DEBUG: 15:45:38 - ConnectAzureRmAccountCommand begin processing with ParameterSet 'UserWithSubscriptionId'.
DEBUG: 15:45:38 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 15:45:38 - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 15:45:38 - Using Autosave scope 'CurrentUser'
Connect-AzAccount : 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 line:1 char:1
+ Connect-AzAccount
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand

DEBUG: AzureQoSEvent: CommandName - Connect-AzAccount; IsSuccess - False; Duration - 00:00:00.0576542;; 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: 15:45:39 - ConnectAzureRmAccountCommand end processing.

PS C:\WINDOWS\system32> Get-AzContext -ListAvailable

Name                                     Account                      SubscriptionName             Environment                  TenantId
----                                     -------                      ----------------             -----------                  --------
Visual Studio Enterprise (xxxxxxxx-xx... xx@xx.se             Visual Studio Enterprise     AzureCloud                   xxxxxxxx-xxxx-xxxx-xxxx-...
Visual Studio Professional (xxxxxxxx-... xx@xx.se             Visual Studio Professional   AzureCloud                   xxxxxxxx-xxxx-xxxx-xxxx-...
DEBUG: 15:46:45 - GetAzureRMContextCommand end processing.

PS C:\WINDOWS\system32> Select-AzContext "Visual Studio Professional (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) - xx@xx.se"
DEBUG: 15:48:45 - SelectAzureRmContext begin processing with ParameterSet 'SelectByName'.
DEBUG: 15:48:45 - Autosave setting from startup session: 'CurrentUser'
DEBUG: 15:48:45 - No autosave setting detected in environment variable 'AzContextAutoSave'.
DEBUG: 15:48:45 - Using Autosave scope 'CurrentUser'
Select-AzContext : 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 line:1 char:1
+ Select-AzContext "Visual Studio Professional (6ef85aca-58ff-44e5-9b43 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Select-AzContext], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.Context.SelectAzureRmContext

DEBUG: AzureQoSEvent: CommandName - Select-AzContext; IsSuccess - False; Duration - 00:00:00.0775886;; 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.Context.SelectAzureRmContext.<>c__DisplayClass8_0.<ExecuteCmdlet>b__0()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ConfirmAction(String processMessage, String target, Action action)
   at Microsoft.Azure.Commands.Profile.Context.SelectAzureRmContext.ExecuteCmdlet()
   at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 15:48:46 - SelectAzureRmContext end processing.

Error output

PS C:\WINDOWS\system32> Resolve-AzError
Resolve-AzError : The default context can no longer be found; please run 'Get-AzContext -ListAvailable' to see all available contexts, 'Select-AzContext' t
o select a new default context, or 'Connect-AzAccount' to login with a new account.
At line:1 char:1
+ Resolve-AzError
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Resolve-AzError], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.Profile.Errors.ResolveError
samme78 commented 4 years ago

I was also in the process of moving my Visual Studio subscription from the old to the new account. So the first time I signed in to the new account I may not have had a subscription yet.

KacperMucha commented 4 years ago

I've got the same issue. But in my case, the problems started after updating Azure Powershell to the newest version.

SolidRockProgrammer commented 4 years ago

I installed latest powershell and azure versions, logged in with one azure account, then could not log off then login with second azure account

dingmeng-xue commented 4 years ago

@samme78, thanks for reporting. could you please try to Connect-AzAccount after you Clear-AzContext?

dingmeng-xue commented 4 years ago

I installed latest powershell and azure versions, logged in with one azure account, then could not log off then login with second azure account

@SolidRockProgrammer , are you meeting the same problem described by @samme78 ?

SolidRockProgrammer commented 4 years ago

@samme78, thanks for reporting. could you please try to Connect-AzAccount after you Clear-AzContext?

running Clear-AzContext resolved my issue

SolidRockProgrammer commented 4 years ago

I installed latest powershell and azure versions, logged in with one azure account, then could not log off then login with second azure account

@SolidRockProgrammer , are you meeting the same problem described by @samme78 ?

I thought so

KacperMucha commented 4 years ago

In my case Clear-AzContext didn't work. Whatever command I try to use I either get:

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.
samme78 commented 4 years ago

I also get the error when running Clear-AzContext. And I cannot do Connect-AzAccount afterwards.

PS C:\gitprojects\temp> Clear-AzContext

Confirm
Remove all accounts and subscriptions in all sessions for the current user?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
Clear-AzContext : The default context can no longer be found; please run 'Get-AzContext -ListAvailable' to see all av
ailable contexts, 'Select-AzContext' to select a new default context, or 'Connect-AzAccount' to login with a new acco
unt.
At line:1 char:1
+ Clear-AzContext
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Clear-AzContext], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.Context.ClearAzureRmContext

PS C:\gitprojects\temp> Connect-AzAccount
Connect-AzAccount : 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 ac
count.
At line:1 char:1
+ Connect-AzAccount
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
erich-wang commented 4 years ago

@samme78, @KacperMucha , could you please manually delete files .Azure\AzureRmContext.json and .Azure\AzureRmContextSettings.json under your user profile folder, normally your profile folder would be:

  1. Windows: c:\users\yourname\
  2. Linux: /home/yourname/
samme78 commented 4 years ago

@erich-wang

It worked, after deleting .Azure\AzureRmContext.json and .Azure\AzureRmContextSettings.json I can once again run Connect-AzAccount.

Thank you

KacperMucha commented 4 years ago

At first, after removing the files, I got:

Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.

when I tried to reconnect. But then I tried Clean-AzContext and Connect-AzContext again, and I was able to run other commands too. One remark though. The test that succeeded was a bit different the previous ones. Earlier I was connecting with Connect-AzAccount -UseDeviceAuthentication -Scope Process, and this time I used only Connect-AzAccount without any parameters. Anyway thank for the tip @erich-wang.

jssimpkins commented 4 years ago

delete files .Azure\AzureRmContext.json and .Azure\AzureRmContextSettings.json worked for me.

Thank you.

jeffdmipshell commented 3 years ago

Deleteting the two files also worked for me.

dingmeng-xue commented 3 years ago

Thanks everyone. Close this issue now. Please contact us if you have further question.