3

Assume I have some powershell code:

function count-pipe {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [object[]]$inputObject
    )

    process {
        $PipeCount = <# How to get count of the pipe? Expect: #> 5

        Write-Output $inputObject # path-throw
    }
}

1..5 | count-pipe | % { $_ }

Yes, I can sum/measure count to temp-variable and use the tee cmdlet. I think this solution make pause the pipe. I think also the temp-valiable is not a good solution relate a memory consumption.

Can I get a pipe objects count without accumulate to temp-variable?

Thanks.

mazzy
  • 1,025
  • 1
  • 13
  • 26
  • How do you intend to use `$PipeCount`, and why isn't `$PipeCount++` a solution? – Jeroen Mostert Aug 08 '17 at 10:44
  • 2
    The point of the pipe is there will be only one object in there at a time so to speak. You are trying to predict the future then? not sure how you would do this without a temp variable – Matt Aug 08 '17 at 10:55

2 Answers2

3

I think using a counter variable is the solution I would use:

function count-pipe {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline=$true)]
        [object[]]$InputObject
    )
    Process {
        $PipeCount++
        $_
    }
    End {
        Write-Verbose $PipeCount
    }

}

'a','b' | count-pipe -verbose | % { $_ }
Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • @Mark Wragg, thanks. Your code get pipe count after pipe complete. Question is: how to get pipe.count inside process? ))) – mazzy Aug 08 '17 at 11:07
  • @gms0ulman, yes. this comment was to previous version answer. With this version pipe.count takes correct value ater cmdlet run ))) Question is: how to get pipe.count inside process? – mazzy Aug 08 '17 at 11:11
  • 1
    How to get pipe count inside `process`? You don't, because the `process` block runs once for each item as each item "arrives" in the pipeline. To count the items, either collect them all beforehand and iterate the collection (like the `foreach` statement) or use a counter (like in this answer). – Bill_Stewart Aug 08 '17 at 14:59
1

Found alternate answer:

Using Measure-Object

Powershell:

@(1,2,3) | Measure-Object

Output:

Count    : 3
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Powershell:

1..5 | Measure-Object -AllStats

Output:

Count             : 5
Average           : 3
Sum               : 15
Maximum           : 5
Minimum           : 1
StandardDeviation : 1.58113883008419
Property          :

For this use case:

Powershell:

$listMeasure = $list | Measure-Object
$listCount = $listMeasure.Count

Examples from here and here

Rohit Mistry
  • 113
  • 3
  • 11