Powershell "select -First 0" 行为
Powershell "select -First 0" behaviour
谁能解释下面代码中 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)。
Select-Object -First 0
或 Select-Object -Last 0
实际上,cmdlet 内部会检查这个确切的场景,并故意不输出任何内容。
您看到 I'm running!
100 次的原因是 Write-Verbose 在 Porcess()
块中。所有 100 个项目都得到处理并且不输出任何内容,因为代码在内部跳过检查 $this.First != 0
然后 Skipp
谁能解释下面代码中 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)。
Select-Object -First 0
或 Select-Object -Last 0
实际上,cmdlet 内部会检查这个确切的场景,并故意不输出任何内容。
您看到 I'm running!
100 次的原因是 Write-Verbose 在 Porcess()
块中。所有 100 个项目都得到处理并且不输出任何内容,因为代码在内部跳过检查 $this.First != 0
然后 Skipp