3

我在一个目录中有六个 .txt 文件。因此,我创建了一个变量:

$foo = gci -Name *.txt

$foo现在是六个字符串的数组。就我而言,我有

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

我想测量那个物体,所以我把它传递给Measure-Object

PS > $foo | Measure-Object

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

这就是我所期待的。但是,我也可能$foo这样通过:

PS> Measure-Object -InputObject $foo

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

这不是我所期待的。这里发生了什么?

4

2 回答 2

8

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.

于 2013-08-28T17:00:32.507 回答
0

PowerShell may be able to help you out here. Let's take a look at Get-Help Measure-Object -full and check out that parameter.

-InputObject <psobject>
    Specifies the objects to be measured. Enter a variable that contains 
    the objects, or type a command or expression that gets the objects.

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       true (ByValue)
    Accept wildcard characters?  false

Pipeline input is accepted by value, so that means that it counts each line of $foo and tallies them. For what it is worth, all of the example usages on Technet and in the Get-Help reference use pipeline input for this parameter.

于 2013-08-28T17:00:13.380 回答