Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'Measure-Object -InputObject $foo' different from '$foo | Measure-Object' in PowerShell?

I have six .txt files in a directory. So, I create a variable thus:

$foo = gci -Name *.txt

$foo is now an array of six strings. In my case I have

PS > $foo
Extensions.txt
find.txt
found_nots.txt
output.txt
proteins.txt
text_files.txt

PS > $foo.gettype()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS > $foo.Count
6

I'd like to measure that object, so I pass it to Measure-Object:

PS > $foo | Measure-Object

Count    : 6
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

That's what I was expecting. However, I might also pass $foo like this:

PS> Measure-Object -InputObject $foo

Count    : 1
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

That's not what I was expecting. What's going on here?

like image 638
WalkingRandomly Avatar asked Feb 02 '26 09:02

WalkingRandomly


1 Answers

When you execute:

$foo | measure-object

PowerShell automatically unrolls collections/arrays and passes each element down the pipeline to the next stage.

When you execute:

measure-object -inputobject $foo

The cmdlet does not internally unroll the collection. This is often times helpful if you want to inspect the collection without having PowerShell do its automatic unrolling. BTW the same thing applies to Get-Member. If you want to see the members on the "collection" instead of each individual element do this:

get-member -inputobject $foo

One way to simulate this in the pipeline case is:

,$foo | Get-Member

This will wrap whatever foo is (collection in this case) in another collection with one element. When PowerShell automatically unrolls that to send elements down the pipeline, the only element is $foo which gets sent down the pipeline.

like image 167
Keith Hill Avatar answered Feb 05 '26 01:02

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!