|
Re: Suggestion: New special variable for pipeline enumeration index Rick already said this, but I'm going to say it again, differently.
There can't be a global variable that represents the "current"
pipeline index, it would have to be "attached" to the pipeline
objects. Let me illustrate in my traditional manner... (and please,
stick with me, even though this is going to look a mess).
# Create and increment $i and write it out
1..6 | &{BEGIN{$global:i = 0}PROCESS{
$global:i++;
$_
}} | &{PROCESS{ # Print out $i
Write-Host ("{0:0.0} $global:i" -f $_) -fore yellow; $_
}} | &{PROCESS{ # This cmdlet outputs 2x
$_ -.5; $_
}} | &{PROCESS{ # Print out $i
Write-Host ("{0:0.0} $global:i" -f $_) -fore green; $_
}} | &{BEGIN{$x=@()} PROCESS{
$x+=$_;
if($x.Count -gt 5){ # stalls the pipeline
$x;
$x=@();
}
}} | &{PROCESS{ # Print out $i
Write-Host ("{0:0.0} $global:i" -f $_) -fore cyan;
}}
If you run that, you'll see that $i increments and prints correctly on
the first (Yellow) Write-Host, but on the second (Green) one, an extra
pipeline element has been introduced, so the $i counter is wrong (and
getting wronger by the minute) ... and on the last (Cyan) one, you'll
only see $i at the multiples of 3.
Even attaching a counter to the pipeline items as they're created
wouldn't work (I left this out of the example, but there could have
been a cmdlet like WHERE-OBJECT which absorbed some of the items) --
PowerShell would have to create and increment a SEPARATE COUNTER for
EACH ELEMENT of the pipeline (that is, for each cmdlet, function,
etc), and in order for it to work properly, it would have pass that
variable to you somehow (maybe by attaching it to the pipeline input
objects?), but it would have to track it itself, and pass it
separately to each pipeline element, because there's no guarantee the
counters would stay correct when they come out the other end of the
element...
So, like I said before ... any cmdlet or script/function that wants to
know how many items it has processed in the current pipeline can
already count them on it's own -- having PowerShell count them would
be complicated, resource intensive, and would basically slow the
pipeline down without providing any additional value. |