管道0..10到高级功能

Pau*_*len 2 powershell

我无法解决为什么0..10直接传递时管道不能通过我的功能.

我希望管道0..10到以下功能将返回10个结果.

function a{param([parameter(ValueFromPipeline=$true)][int[]]$t)$t|%{$_+10}}
0..10 | a
Run Code Online (Sandbox Code Playgroud)

我不明白为什么以下只返回一个结果.

我预计会通过管道传输一个值块并将其$t | %{$_+10}分解,对它们进行操作并将它们返回到输出.

如果我执行以下操作,它会按预期工作

a(0..10)
Run Code Online (Sandbox Code Playgroud)

我不认为有什么不对,只是因为我不明白什么0..10是什么,并希望得到社区的一些帮助.

Chr*_*wis 6

理解这一点的最好方法是没有高级功能

BEGIN {}
PROCESS {}
END {}
Run Code Online (Sandbox Code Playgroud)

在接受管道和数组时,结构非常混乱.

这里发生的是没有PROCESS {}块,函数中的$ T是INT [],并作为数组传递.你的foreach进程,但返回命令的最后结果 - 10 + 10

将代码更改为:

function a{ 
   param([parameter(ValueFromPipeline=$true)][int[]]$t)
   BEGIN {}
   PROCESS{       
     $t | %{$_+10}
   }
   END {}
}
Run Code Online (Sandbox Code Playgroud)

返回您期望的内容 - $ T的每个元素都传递给foreach,然后传递给管道.

以下是来自MS PowerShell之一的链接:Windows PowerShell:高级功能生命周期显示了一些很好的示例.

阅读下面的@Chris-Magnuson链接,我想出了一些很好的代码,可以准确地显示正在发生的事情:

Function AA {
    Begin {"Begin: The input is $input , Pipeline is $_"}
    End   {"End:   The input is $input , Pipeline is $_" }
}

PS C:\Temp> 1,2,3 | AA
Begin: The input is  , Pipeline is 
End:   The input is 1 2 3 , Pipeline is 

Function BB {
    Begin   {"Begin:   The input is $input , Pipeline is $_" }
    Process {"Process: The input is $input , Pipeline is $_" }
    End     {"End:     The input is $input , Pipeline is $_" }
}

PS C:\Temp> 1,2,3 | BB
Begin:   The input is  , Pipeline is 
Process: The input is 1 , Pipeline is 1
Process: The input is 2 , Pipeline is 2
Process: The input is 3 , Pipeline is 3
End:     The input is  , Pipeline is 3
Run Code Online (Sandbox Code Playgroud)

我会说,有点时髦.