Home > Mobile >  How to define an alias for a command with options in a Powershell Profile using functions?
How to define an alias for a command with options in a Powershell Profile using functions?

Time:12-13

I already have a bunch of command aliases defined for git. Here's all of them:

del alias:gp -Force
del alias:gl -Force
del alias:gcm -Force

function get-gst { git status }
set-alias -name gst -value get-gst

function get-gco ([string]$branch) { 
    git checkout "$branch"
}
set-alias -name gco -value get-gco 

function get-gcob ([string]$branch) { 
    git checkout -b "$branch"
}
set-alias -name gcob -value get-gcob

function get-gp { git push }
set-alias -name gp -value get-gp 

function get-gl { git pull }
set-alias -name gl -value get-gl 

function get-gcm ([string]$message) { 
    git commit -m "$message"
}
set-alias -name gcm -value get-gcm 

function get-ga ([string]$path) { 
    git add "$path"
}
set-alias -name ga -value get-ga

function get-gap { git add --patch }
set-alias -name gap -value get-gap

function get-gsta { git stash push }
set-alias -name gsta -value get-gsta 

function get-gstp { git stash pop }
set-alias -name gstp -value get-gstp 

function get-glo { git log --oneline }
set-alias -name glo -value get-glo 

function get-a ([string]$option, [string]$option2, [string]$option3) { 
    php artisan "$option" "$option2" "$option3"
}
set-alias -name a -value get-a

Specifically, this is the content of Powershell's $Profile.AllUsersAllHosts

Currently, I have 2 separate functions for git checkout branch and git checkout -b branch. The aliases are respectively gco branch and gcob branch.

What I would like to have is a function similar to the last alias in my list (the one for php artisan), such that I can have something like this:

function get-gco ([string]$option, [string]$option2) { 
    git checkout "$option" "$option2"
}
set-alias -name gco -value get-gco 

..that would allow me to write gco -b branch or in fact pass any other option to the git checkout command. Unfortunately this does not work and upon writing gco -b newBranchName nothing happens (it is as if I have only written git chekout), but it does work if I would write gco "-b" newBranchName or gco '-b' newBranchName.

Do you think it's possible to make the function such that the quotes aren't needed in Powershell and how would you go about doing it? Alternatively would it be possible in another command-line interface, like for example git bash?

CodePudding user response:

Splat the $args automatic variable:

function get-gco {
    git checkout @args
}

This will pass any additional arguments to git checkout as-is, so now you can do either:

get-gco existingBranch
# or
get-gco -b newBranch

... with the same function

  • Related