PowerShell Quiz

by Doug Finke on July 17, 2008

in PowerShell, Quiz

Fellow Lab49er Daniel Simon asked why the different results?
PS > $a=1,(2,3)
PS > $a.Count
2
PS > ($a | % {$_}).count
3

What do you think?

{ 4 comments… read them below or add one }

1 Steven Murawski 07.18.08 at 7:52 am

I believe it is because PowerShell “flattens” arrays when sending them down the pipeline, so you end up with all three elements in the second case.

2 Grant Steinfeld 07.18.08 at 12:29 pm

a is an array with a value of 1 and an array with the numbers 2 and 3
so it has two items
when you pipe it to a for each (%) you are with () so essentially you are creating a new array with the values 1,2,3 so hence the new count of the anonymous array is 3

3 Mat Hobbs 07.18.08 at 10:28 pm

To paraphrase Steven: If the rule is:

‘Send to pipe’ on an array (or enumerable) means send down the pipe its elements separately (i.e. ‘flatten’).

First, per the rule, “$a |” sends two elements down: 1 and then (2,3). Then “%{…}” will process both as simply ’send to the pipe’ again (which is what “$_” does) which means do ’send to pipe’ on “1″ and then ’send to pipe’ on “(2,3)”. Send to pipe on “(2,3)” means to send 2 and 3 separately according to the rule again. So three things end up in all (before being wrapped as an output and told to .count).

4 m473i 01.29.10 at 8:38 am

yep..
it’s because “1″ and “(2,3)” represent 2 objects: “1″ is int32 and “(2,3)” is the array
in the other hand, when you use foreach loop, you are working with whole pipeline input, which, actually, contains 3 objects together

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>