PowerShellでAzureサブスクリプションの切り替えを楽にする
azure powershellAzureサブスクリプションを複数管理していると、
サブスクリプションを切り替えるときに az account set --subscription {id}
を打つと思います。
しかしこのコマンド、結構長いのと、 サブスクリプションのIdをなかなか覚えておくことができないので、 毎回az account listを打ってidをコピペしているのがなかなかつらいです。
そこで、ログインしているサブスクリプションの名前一覧の中から、 矢印キーで選択できるようにするfunctionを作ってみました
function az-s {
$subscList = az account list | ConvertFrom-Json
function ShowAccountList {
param([int] $SelectIndex)
foreach ($subsc in $subscList) {
$index = $subscList.IndexOf($subsc)
$isSelected = $SelectIndex -eq $index
$cursor = $isSelected ? "👉 " : ""
$color = $isSelected ? "Cyan" : "White"
Write-Host "$cursor$($subsc.name)" -ForegroundColor $color
}
}
$currentSelectIndex = 0
while ($true) {
Clear-Host
Write-Host "Select Subscription" -BackgroundColor "Cyan"
Write-Host ""
ShowAccountList -SelectIndex $currentSelectIndex
Write-Host ""
Write-Host "press [q] to quit"
$key = [Console]::ReadKey($true)
if ($key.Key -eq "UpArrow" -and $currentSelectIndex -gt 0) {
$currentSelectIndex--
}
if ($key.Key -eq "DownArrow" -and $currentSelectIndex -lt ($subscList.Length - 1)) {
$currentSelectIndex++
}
if ($key.Key -eq "Enter") {
$subsc = $subscList[$currentSelectIndex]
Write-Host ""
Write-Host "$($subsc.name) selected!" -ForegroundColor "Yellow"
az account set --subscription $subsc.id
break
}
if ($key.Key -eq "q" -or $key.Key -eq "Q") {
break
}
}
}