1

I am trying to write some PowerShell aliases in my profile.ps1 file. The problem is that I can not get commands with a variable number of parameters to work properly.

For example, I want to have an alias that links "kg" to "kubectl get", which is followed by a resource and sometimes an option. So "kg pods -A" and "kg pod" should both work afterwords.

According to this post, I need to define a function that can be seen below, my problem is that it ignores all arguments after the first. So "kg pods -A" returns the result of "kg pods". This post explains how to pass multiple arguments to a function, up it does not work for some reason. (I am using Powershell in Cmder if this is relevant). Could it be that the "-" causes an issue?

The relevant part of the "profile.ps1":

Function get ($restOfLine, $restOfLine2) { kubectl get $restOfLine $restOfLine2}
Set-Alias kg get

1 Answer 1

2

As soon as you explicitly declare parameters in a function, PowerShell will attempt to bind input arguments to those parameters, by parsing the command invocation expression and treating any sequence starting with - as a parameter name.

Remove the parameters and pass $args directly to avoid this interference:

function get { kubectl get @args }
Set-Alias kg get

kg post -A will now pass post and -A to kubectl as-is

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.