Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Last active May 29, 2020 19:01
Show Gist options
  • Save JustinGrote/943a2578555a439ce2d8a99bda958bb9 to your computer and use it in GitHub Desktop.
Save JustinGrote/943a2578555a439ce2d8a99bda958bb9 to your computer and use it in GitHub Desktop.
A helper command to quickly switch current Azure Contexts
using namespace System.Management.Automation.Host
function Switch-AzContext {
param (
[Parameter(ValueFromPipeline)]
[Microsoft.Azure.Commands.Profile.Models.Core.PSAzureContext[]]
[ValidateNotNullOrEmpty()]
$Contexts = (Get-AzContext -ListAvailable | Sort-Object Name),
[Switch]$GUI
)
$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 | 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 | 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]
}
Set-AzContext -Context $ContextToSet > $null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment