Skip to content

Commit d987ad5

Browse files
authored
Fixed a null reference issue during the process of Get-AzContext -ListAvailable (#24865)
* Fixed a null reference issue during the process of Get-AzContext -ListAvailable [#24854] * Update src/Accounts/Accounts/Context/GetAzureRMContext.cs
1 parent ee1cd54 commit d987ad5

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/Accounts/Accounts/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
-->
2020

2121
## Upcoming Release
22+
* Fixed a null reference issue during the process of `Get-AzContext -ListAvailable` [#24854].
2223
* Supported interactive subscription selection for user login flow. See more details at [Announcing a new login experience with Azure PowerShell and Azure CLI
2324
](https://techcommunity.microsoft.com/t5/azure-tools-blog/announcing-a-new-login-experience-with-azure-powershell-and/ba-p/4109357)
2425
* Added config `LoginExperienceV2` to allow customer to switch the default behavior of context selection back. Check the help document of `Update-AzConfig` for more details.

src/Accounts/Accounts/Context/GetAzureRMContext.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ public override void ExecuteCmdlet()
104104
var profile = DefaultProfile as AzureRmProfile;
105105
if (profile != null && profile.Contexts != null)
106106
{
107-
WritePSAzureContext(profile.Contexts.Select(context => ToPSAzureContext(context.Value, context.Key)).
108-
OrderBy(context => context.Tenant.Id).ThenBy(context => context.Subscription.Name));
107+
WritePSAzureContext(profile.Contexts.Select(context => ToPSAzureContext(context.Value, context.Key))?.Where(context => null != context) // remove null contexts
108+
?.OrderBy(context => context?.Tenant?.Id ?? "").ThenBy(context => context?.Subscription?.Name ?? ""));
109109
}
110110

111111
}
@@ -129,10 +129,17 @@ public override void ExecuteCmdlet()
129129
}
130130
}
131131

132+
/// <summary>
133+
/// Convert AzureContext to PSAzureContext with given name
134+
/// Notice that returned context may be null
135+
/// </summary>
136+
/// <param name="azureContext"></param>
137+
/// <param name="name"></param>
138+
/// <returns></returns>
132139
private PSAzureContext ToPSAzureContext(IAzureContext azureContext, string name)
133140
{
134141
var context = new PSAzureContext(azureContext);
135-
if (name != null)
142+
if (null != name && null != context)
136143
{
137144
context.Name = name;
138145
}

0 commit comments

Comments
 (0)