-
-
Save kpatnayakuni/faef5d2d887a1ba43ffef72bde413d6f to your computer and use it in GitHub Desktop.
A helper command to quickly switch current Azure Contexts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Management.Automation.Host | |
function Switch-AzContext | |
{ | |
[CmdLetBinding(DefaultParameterSetName = 'By Context')] | |
param ( | |
[Parameter(ParameterSetName = 'By Name')] | |
[Alias('Context', 'ContextName')] | |
[ValidateNotNullOrEmpty()] | |
[ArgumentCompleter( { | |
return (Get-AzContext -ListAvailable | Where-Object { $_.Subscription.Name -ne (Get-AzContext).Subscription.Name } | ForEach-Object { "'" + ($_.Subscription.Name.ToString()) + "'" } ) | |
})] | |
[string] $Name, | |
[Parameter(ValueFromPipeline, ParameterSetName = 'By Context')] | |
[ValidateNotNullOrEmpty()] | |
[psobject[]] $Contexts = (Get-AzContext -ListAvailable | Sort-Object Name), | |
[Parameter(ParameterSetName = 'By Context')] | |
[Switch] $GUI | |
) | |
if ($PSCmdlet.ParameterSetName -eq 'By Name') | |
{ | |
$null = Set-AzContext -Subscription $Name | |
return | |
} | |
$currentContext = Get-AzContext | |
if (-not $Contexts) { throw 'No Contexts available, run Connect-AzAccount first!' } | |
if ($Contexts.count -eq 1) { Write-Warning "Context $($Contexts.Name) the only context available"; return } | |
$defaultIndex = 0 | |
$i = 1 | |
$ContextToSet = if ($GUI -and (Get-Command 'Out-Gridview' -ErrorAction SilentlyContinue)) | |
{ | |
$Contexts | Where-Object { $_.Subscription.Name -ne $currentContext.Subscription.Name } | Out-GridView -OutputMode Single -Title "Select a new Default Azure Context" | |
} | |
elseif ($psedition -ne 'Desktop' -and -not $IsWindows -and (Get-Command 'Out-ConsoleGridview' -ErrorAction SilentlyContinue)) | |
{ | |
$Contexts | Where-Object { $_.Subscription.Name -ne $currentContext.Subscription.Name } | Out-ConsoleGridview -OutputMode Single -Title "Select a new Default Azure Context" | |
} | |
else | |
{ | |
[ChoiceDescription[]]$contextPrompts = $Contexts.foreach{ | |
[ChoiceDescription]::New("&$i $($PSItem.Name)") | |
if ($PSItem.Name -eq $currentContext.Name) | |
{ | |
$defaultIndex = $i - 1 | |
} | |
$i++ | |
} | |
$result = $Host.UI.PromptForChoice( | |
$null, #caption | |
'Select a new Default Azure Context' + [Environment]::NewLine + '==================================', #message | |
$ContextPrompts, #choices | |
$defaultIndex #defaultChoice | |
) | |
$Contexts[$result] | |
} | |
$null = Set-AzContext -Context $ContextToSet | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment