向 PowerShell 别名函数添加参数

Adding Arguments to PowerShell Alias Functions

我刚刚通过 chocolatey 在 PowerShell 上安装了 grep 并使用它,我可以从任何文本中搜索我想要的字符串,如下所示:

但是,我不想总是输入 grep --color,因此我尝试在我的 $profile 上创建一个别名,如下所示:

Function grep($a1){
  grep --color $a1
}

但是我会得到一个错误:

所以我尝试了:

Set-Alias grep "grep --color"

但是我又遇到了另一个错误:

我想不出任何其他方法来完成这项工作,因此非常感谢任何帮助。

PowerShell 中的

Aliases 只是其他命令的替代 names,因此您不能使用它们来包含 arguments 传递给这些其他命令。

因此您确实需要一个 函数 ,但是由于您将其命名为与您包装的外部程序相同的名称,因此您需要消除歧义以避免无限递归:

function grep {
  $externalGrep = Get-Command -Type Application grep
  if ($MyInvocation.ExpectingInput) { # pipeline (stdin) input present
    # $args passes all arguments through.
    $input | & $externalGrep --color $args
  } else {
    & $externalGrep --color $args
  }
}

注:

  • 使用 automatic $input variable to relay pipeline (stdin) input means that this input is collected (buffered) in full first. More effort is needed to implement a true streaming solution - see 作为示例。

或者 - 至少在 Unix-like 平台上 - 你可以设置一个 environment 变量来控制 grep 的着色行为,这可能会避免需要对于函数包装器; --color 参数的等效项是设置 $env:GREP_COLOR='always'(其他支持的值是 'never''auto')。