N N
N N

Reputation: 1638

How do I set an alias for a specific command in Powershell?

There is a command that I type a lot: java -jar foo --param1 --param2, --param-n. How can I create a command alias to run this command like so:

launch_foo --param3

where launch_foo is translated to the full command?

Upvotes: 6

Views: 8741

Answers (2)

Floris
Floris

Reputation: 3127

You could also, for example create a launch_foo.bat file inside any bin folder that is in the environment variabel PATH location.

Then inside the launch_foo.bat file you place the command for example: java -jar foo %*.

The %* is for all argument that comes after the initial command. You could also user %1 if you only want to use the first argument.

Now you can call the launch_foo --param3 command from Powershell. For me this solution works like a charm on Windows.

Upvotes: 0

codewario
codewario

Reputation: 21408

You have to create a function. Fortunately, creating an "alias-style" function with standard arguments isn't difficult:

Function launch_foo { java -jar foo --param1 --param2 --param-n $args }

You can now invoke the function either as launch_foo or as launch_foo --param3. Note that if you don't pass in any additional arguments, $args will be $null and will have no effect[1] on the default arguments specified in the function.

Now, there is the concept of aliases in Powershell but aliases are alternate names for cmdlets or commands, you can't add arguments to the alias definition. You would use an alias as an alternate executable or cmdlet name. Some examples of aliases:

Set-Alias v vim
Set-Alias list Get-ChildItem
Set-Alias 2json ConvertTo-Json

v would run vim, list would run Get-ChildItem, and 2json would run ConvertTo-Json.


[1] Note that this is only true for external commands. If you attempt to alias a cmdlet or function with parameters in this way, a $null argument will be evaluated as a $null value, which $args would be $null if not provided. Depending on the cmdlet this could throw an error, have no effect, or have an undesired effect. Depending on the cmdlet, you may also need to splat @args to appropriately pass on the arguments.

Upvotes: 9

Related Questions