How to make an alias for Kubectl in Windows using ENV Variables?

Viewed 1871

I've created a folder called Aliases in C:\ and added C:\Aliases to Environment Variables. Inside the folder I've created a file K.bat with contents :

kubectl

however when I run k get pods it doesn't return a string , only executes the kubectl command without any parameters after it.

How can we fix this ?

3 Answers

The simpler anwser is to rename the kubectl command or use doskey you can execute this at startup.

doskey k=kubectl $*

You can use %* to pass on all command line arguments in a batch script.

Therefore, your k.bat or k.cmd file would look like this:

@echo off
kubectl %*

This will create you the k alias for kubectl on Windows.

I have a similar shortcut for minikube, with some added logic for determining if the parameter should be sent to minikube or kubectl:

@echo off
set DIRECT_COMMANDS=:start:status:stop:delete:dashboard:pause:unpause:docker-env:podman-env:cache:image:addons:config:profile:update-context:service:tunnel:mount:ssh:kubectl:node:ssh-key:ssh-host:ip:update-check:version:options:completion:

echo:%DIRECT_COMMANDS%|findstr /c::%1% >NUL 2>&1

if %ERRORLEVEL%==0 (
  minikube %*
) else (
  minikube kubectl -- %*
)

And if you want a command with agruments to be treated as macros, use "$*" in the end, like you do it with alias in *nix:

alias kn='kubectl config set-context --current --namespace'

with doskey will be:

doskey kn=kubectl config set-context --current --namespace "$*
Related