繁体   English   中英

Powershell:转发 arguments 和管道输入到别名 function

[英]Powershell: Forward arguments and pipeline input to alias function

如何将所有管道输入和 arguments 转发到别名 function 内的命令。

例如,如果我想给 tail 起别名

function tail {
  coreutils tail @args
}

tail -n 5 test.txt一起工作正常

但不是cat test.txt | tail -n 5 cat test.txt | tail -n 5

即使cat test.txt | coreutils tail -n 5 cat test.txt | coreutils tail -n 5作品

在最简单的情况下,使用以下命令:

function tail {
  if ($MyInvocation.ExpectingInput) { # Pipeline input present.
    # $Input passes the collected pipeline input through.
    $Input | coreutils tail @args
  } else {
    coreutils tail @args
  }
}

这种方法的缺点是所有管道输入首先收集在 memory 中,然后再中继到目标程序。


流式解决方案——输入对象(行)在可用时通过——需要更多的努力:

function tail {
  [CmdletBinding(PositionalBinding=$false)]
  param(
      [Parameter(ValueFromPipeline)]
      $InputObject
      ,
      [Parameter(ValueFromRemainingArguments)]
      [string[]] $PassThruArgs
  )
  
  begin
  {
    # Set up a steppable pipeline.
    $scriptCmd = { coreutils tail $PassThruArgs }  
    $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
    $steppablePipeline.Begin($PSCmdlet)
  }
  
  process
  {
    # Pass the current pipeline input through.
    $steppablePipeline.Process($_)
  }
  
  end
  {
    $steppablePipeline.End()
  }
  
}

上述高级 function是所谓的代理 function ,在这个答案中有更详细的解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM