Created
June 13, 2022 11:11
-
-
Save krokofant/61583219cfe84fea16f5f0573e3c637f to your computer and use it in GitHub Desktop.
Easily change between kubectl versions on PowerShell
This file contains hidden or 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
function Use-Kubectl { | |
[CmdletBinding()] | |
param ( | |
[Parameter(ValueFromPipeline, Mandatory)] | |
[ArgumentCompleter({ | |
param ( | |
$CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters | |
) | |
$versions = Invoke-RestMethod "https://api.github.com/repos/kubernetes/kubernetes/releases" | |
$stableVersions = $versions | Where-Object -Property prerelease -EQ $false | Select-Object -ExpandProperty tag_name | ForEach-Object { $_.Substring(1) } | Sort-Object -Descending | |
$stableVersions | Where-Object { $_.StartsWith($WordToComplete) } | |
})] | |
[string]$Version | |
) | |
$DownloadUrl = "https://dl.k8s.io/release/v$($Version)/bin/windows/amd64/kubectl.exe" | |
if (-not (Test-Path ~/bin/kubectl)) { New-Item -Type Directory ~/bin/kubectl -Force | Out-Null } | |
if (-not (Test-Path "~/bin/kubectl/$Version")) { | |
New-Item -Type Directory "~/bin/kubectl/$Version" | Out-Null | |
Write-Host "Downloading version $Version" | |
Invoke-WebRequest $DownloadUrl -OutFile "~/bin/kubectl/$Version/kubectl.exe" | |
} | |
$newPath = $env:Path.Split(';') | Where-Object { $_ -notlike "$(Resolve-Path ~/bin/kubectl)*" } | |
$newPath = @("$(Resolve-Path "~/bin/kubectl/$Version")") + $newPath | |
$env:Path = $newPath -join ';' | |
Write-Host "Now using $Version from ~/bin/kubectl/$Version/kubectl.exe" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment