Powershell "select -First 0"
Can someone please explain what is happening in the example select -first 0
in the code below?
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`.
If we add the -verbose switch, we can see that the value $global:x
corresponds to the number of iterations according to the detailed result (i.e. we get 10 verbose messages in the first example, 100 in the second and 100 in the third).
source to share
Select-Object -First 0
or Select-Object -Last 0
Actually, the cmdlets internally have a check for this exact scenario and intentionally don't output anything.
the reason you see I'm running!
for 100 times is that the Write-Verbose is in the block Porcess()
. All 100 elements are processed and do not place anything as the code internally skips on the check $this.First != 0
, then Skipp
source to share