How to get count of pipe objects? I don't want accumulate pipe to buffer

Viewed 1131

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.

2 Answers

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

Related