[英]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.