Alias a command in Windows Terminal using Powershell as the default profile

506 views Asked by At

I want to alias the following 2 commands (combining ssh with fuzzy finder) in the Windows Terminal which uses the default profile as PowerShell:

fzf_ssh: ssh $(cat .ssh_known_hosts | fzf)
fzf_ssh_tmux: ssh $(cat .ssh_known_hosts | fzf) -t tmux a

(The file .ssh_known_hosts is a file I created with the username@hostname entries)


I found the following article, but they are aliasing it for cmd: save-your-precious-dev-time-with-command-aliases-in-windows-terminal.


The following post suggests updating the $profile file of PowerShell with Set-Alias: windows_terminal_how_do_you_set_aliass
I made the following entry in the $profile file:

Set-Alias -Name fzf_ssh -Value ssh $(cat .ssh_known_hosts | fzf)
Set-Alias -Name fzf_ssh_tmux -Value ssh $(cat .ssh_known_hosts | fzf) -t tmux a

But on launching a new Windows Terminal session, the commands get executed and open the fuzzy finder which is not what I want. I just want it to alias those 2 commands.


How can I achieve this?

1

There are 1 answers

0
mklement0 On BEST ANSWER

You must define functions rather than aliases, because in PowerShell an alias is simply another name for a command, and therefore doesn't support passing arguments:

function fzf_ssh      { ssh (cat .ssh_known_hosts | fzf) }
function fzf_ssh_tmux { ssh (cat .ssh_known_hosts | fzf) -t tmux a }

See this answer for background information.


As for what you tried:

  • Since an alias is just another name for a command, the -Value parameter of Set-Alias accepts just one argument, namely the name of the command for which to create the alias.

  • The command enclosed in $(...), the subexpression operator, is executed instantly (as an aside: (...), the grouping operator, as used above, is usually sufficient).

  • Thereafter, your attempt to (positionally) pass additional arguments ($(...)) to Set-Alias ultimately causes a syntax error (A positional parameter cannot be found ...).