首页 > 解决方案 > 试图将我的头脑围绕在 PowerShell 上——函数、别名等

问题描述

我是一名经验丰富的 C# 程序员,但到目前为止,我只涉足 PowerShell(迄今为止使用过另一个替代的 Windows 命令行产品)。

我正在尝试自动化一些 Git 的东西,但我遇到了一些困难,似乎找不到任何解决方案......(到目前为止,似乎没有视频教程或博客文章有太大帮助) .

我想要做的是定义函数和别名,使我在 PowerShell 中使用 Git 更加舒适——是的,我知道Posh-Git,并且也已经检查过了——但这似乎主要是处理呈现PowerShell 中的一个不错的 UI。

我想为我一直使用的常见 Git 命令定义“快捷方式” - 并且到目前为止已经成功定义了一些别名。

我现在正在苦苦挣扎的是:我想为git pull(and also git push) 设置一个别名,它可以“按原样”运行 - 例如运行 just git pull,或者可以运行我需要的最频繁的命令使用 - git pull origin master

我试图定义一个函数:

function invoke-gitpull { git pull $args }

然后为此定义两个别名——一个只是“按原样”调用这个函数,一个提供两个参数——像这样:

Set-Alias gtp invoke-gitpull 
Set-Alias gtpom invoke-gitpull origin master

但不知何故,PS不喜欢这样:-(

Set-Alias:找不到接受参数“原点”的位置参数。
+ Set-Alias gtpom invoke-gitpull origin master
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Alias], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetAliasCommand

然后我还尝试为invoke-gitpull函数定义参数 - 如下所示:

function invoke-gitpull ([String] $remote, [String] $branch) { git pull $remote $branch }

认为如果我不提供参数值,那么git pull将被发布-如果我提供两个参数值- invoke-gitpull -remote origin -branch master,那么git pull origin master将被调用-但同样,PS不同意我的观点:

设置别名:找不到与参数名称“远程”匹配的参数。
+ Set-Alias gtpom invoke-gitpull -remote origin -branch master
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Alias], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetAliasCommand

然后我还尝试了函数内部的参数:

但我又遇到了同样的错误。

那么我必须如何为我的invoke-gitpull函数定义这些参数才能使其工作?我似乎在兜圈子,不完全理解我做错了什么......谁能启发我?

标签: gitfunctionpowershellalias

解决方案


别名(使用cmdlet)仅限*-Alias于指向命令名称,没有参数。如果您希望将别名的参数作为另一个别名(例如),则需要将它们定义为函数gtp origin master

function invoke-gitpull { git pull $args }
Set-Alias -Name gtp -Value invoke-gitpull
function gtpom { gtp origin master }

但如果这只是一个私人使用的东西,我会跳过别名,只是将它们包含在$Profile你想要的方式中:

function gtp() { & GIT.exe pull @args }
function gtpom() { gtp origin master }

推荐阅读