Powershell:将参数和管道输入转发到别名函数



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

例如,如果我想别名尾部

function tail {
coreutils tail @args
}

适用于tail -n 5 test.txt

但不使用cat test.txt | 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
}
}

这种方法的缺点是在将所有管道输入中继到目标程序之前,首先将其收集在内存中


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

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()
}

}

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

最新更新