Joh*_*van 5 powershell powershell-5.0
谁能解释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`.
Run Code Online (Sandbox Code Playgroud)
如果我们添加 -verbose 开关,我们会看到 的值与$global:x根据详细输出的迭代次数相匹配(即,我们在第一个示例中获得 10 条详细消息,在第二个示例中获得 100 条详细消息,在第三个示例中获得 100 条)。
Select-Object -First 0或者Select-Object -Last 0
实际上,cmdlet 在内部会检查这种确切的情况,并故意不输出任何内容。
您看到 100 次的原因I'm running!是 Write-Verbose 处于Porcess()阻塞状态。所有 100 个项目都得到处理,并且不输出任何内容,因为代码在内部跳过检查,$this.First != 0然后跳过
| 归档时间: |
|
| 查看次数: |
6932 次 |
| 最近记录: |