Powershell“选择-第一个0”行为

Powershell“选择-第一个0”行为,powershell,powershell-5.0,Powershell,Powershell 5.0,有人能解释一下下面代码中的select-first 0示例发生了什么吗 Function Test-Example { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] $InputObject ) process { $global:x++ write-verbose 'I''m running!' $I

有人能解释一下下面代码中的select-first 0示例发生了什么吗

Function Test-Example {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $InputObject
    )
    process {
        $global:x++
        write-verbose 'I''m running!'
        $InputObject
    }
}

[int]$global:x = 0 #reset the counter
1..100 | Test-Example -Verbose | select -first 10
$global:x #outputs 10

$global:x = 0 #reset the counter
1..100 | Test-Example | select -first 1000
$global:x #outputs 100; as we only iterate 100 times depsite asking for the first 1000

$global:x = 0 #reset the counter
1..100 | Test-Example | select -first 0 
$global:x #outputs 100; which doesn't make sense since we don't see any output, suggesting `select -first 0` behaves like `select * | out-null`.
如果我们添加-verbose开关,我们会看到$global:x的值与根据详细输出的迭代次数相匹配,也就是说,我们在第一个示例中得到10条详细消息,在第二个示例中得到100条,在第三个示例中得到100条。

选择对象-第一个0或选择对象-最后一个0

实际上,cmdlet在内部检查了这个确切的场景,并故意不输出任何内容


你看到我跑步的原因!在进程块中写入详细信息达100次。当代码在内部跳过$this.First!=0然后跳过

您的函数不处理管道取消,因此它会处理整个输入。不过这只是猜测。应该会有帮助。说:_首先!=0因此,当您指定-First 0时,管道并没有停止;有趣的管道取消阅读。如果我理解的话:取消上游命令的唯一方法是中断当前代码;这需要管道之外的东西来打破或捕获异常。还要感谢@PetSerAl提供了指向代码/罪魁祸首的链接。似乎通过在C中编写此语句,管道取消限制并不是一个问题,也就是说,不要求任何使用select object-first的人在该语句周围包含代码以突破或捕获任何异常,因此问题仍然存在,为什么MS会明确地说_first!=在这种情况下为0,除非这是一个疏忽,因为-第一个0是一个奇怪的用例;虽然根据ValidateRange允许,但应支持。