问题
Let\'s say we have an array of objects $objects. Let\'s say these objects have a \"Name\" property.
This is what I want to do
$results = @()
$objects | %{ $results += $_.Name }
This works, but can it be done in a better way?
If I do something like:
$results = objects | select Name
$results is an array of objects having a Name property. I want $results to contain an array of Names.
Is there a better way?
回答1:
I think you might be able to use the ExpandProperty parameter of Select-Object.
For example, to get the list of the current directory and just have the Name property displayed, one would do the following:
ls | select -Property Name
This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).
ls | select -Property Name | gm
So, to expand the object to be that of the type of property you're looking at, you can do the following:
ls | select -ExpandProperty Name
In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:
$objects = ls | select -ExpandProperty Name
回答2:
As an even easier solution, you could just use:
$results = $objects.Name
Which should fill $results with an array of all the 'Name' property values of the elements in $objects.
回答3:
To complement the preexisting, helpful answers with guidance of when to use which approach and a performance comparison.
Outside of a pipeline, use:
$objects.Name
(PSv3+), as demonstrated in rageandqq's answer, which is both syntactically simpler and much faster.- Accessing a property at the collection level to get its members' values as an array is called member enumeration and is a PSv3+ feature.
- Alternatively, in PSv2, use the
foreachstatement, whose output you can also assign directly to a variable:$results = foreach ($obj in $objects) { $obj.Name } - Tradeoffs:
- Both the input collection and output array must fit into memory as a whole.
- If the input collection is itself the result of a command (pipeline) (e.g.,
(Get-ChildItem).Name), that command must first run to completion before the resulting array's elements can be accessed.
In a pipeline where the result must be processed further or the results don't fit into memory as a whole, use:
$objects | Select-Object -ExpandProperty Name
- The need for
-ExpandPropertyis explained in Scott Saad's answer. - You get the usual pipeline benefits of one-by-one processing, which typically produces output right away and keeps memory use constant (unless you ultimately collect the results in memory anyway).
- Tradeoff:
- Use of the pipeline is comparatively slow.
- The need for
For small input collections (arrays), you probably won't notice the difference, and, especially on the command line, sometimes being able to type the command easily is more important.
Here is an easy-to-type alternative, which, however is the slowest approach; it uses simplified ForEach-Object syntax called an operation statement (again, PSv3+): ; e.g., the following PSv3+ solution is easy to append to an existing command:
$objects | % Name # short for: $objects | ForEach-Object -Process { $_.Name }
For the sake of completeness: The little-known PSv4+ .ForEach() array method, more comprehensivel discussed in this article, is yet another alternative:
# By property name (string):
$objects.ForEach('Name')
# By script block (more flexibility; like ForEach-Object)
$objects.ForEach({ $_.Name })
This approach is similar to member enumeration, with the same tradeoffs, except that pipeline logic is not applied; it is marginally slower, though still noticeably faster than the pipeline.
For extracting a single property value by name (string argument), this solution is on par with member enumeration (though the latter is syntactically simpler).
The script-block variant, allows arbitrary transformations; it is a faster - all-in-memory-at-once - alternative to the pipeline-based
ForEach-Objectcmdlet (%).
Comparing the performance of the various approaches
Here are sample timings for the various approaches, based on an input collection of 10,000 objects, averaged across 10 runs; the absolute numbers aren't important and vary based on many factors, but it should give you a sense of relative performance (the timings come from a single-core Windows 10 VM:
Important
The relative performance varies based on whether the input objects are instances of regular .NET Types (e.g., as output by
Get-ChildItem) or[pscustomobject]instances (e.g., as output byConvert-FromCsv).
The reason is that[pscustomobject]properties are dynamically managed by PowerShell, and it can access them more quickly than the regular properties of a (statically defined) regular .NET type. Both scenarios are covered below.The tests use already-in-memory-in-full collections as input, so as to focus on the pure property extraction performance. With a streaming cmdlet / function call as the input, performance differences will generally be much less pronounced, as the time spent inside that call may account for the majority of the time spent.
For brevity, alias
%is used for theForEach-Objectcmdlet.
General conclusions, applicable to both regular .NET type and [pscustomobject] input:
The member-enumeration (
$collection.Name) andforeach ($obj in $collection)solutions are by far the fastest, by a factor of 10 or more faster than the fastest pipeline-based solution.Surprisingly,
% Nameperforms much worse than% { $_.Name }- see this GitHub issue.PowerShell Core consistently outperforms Windows Powershell here.
Timings with regular .NET types:
- PowerShell Core v7.0.0-preview.3
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.005
1.06 foreach($o in $objects) { $o.Name } 0.005
6.25 $objects.ForEach('Name') 0.028
10.22 $objects.ForEach({ $_.Name }) 0.046
17.52 $objects | % { $_.Name } 0.079
30.97 $objects | Select-Object -ExpandProperty Name 0.140
32.76 $objects | % Name 0.148
- Windows PowerShell v5.1.18362.145
Comparing property-value extraction methods with 10000 input objects, averaged over 10 runs...
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.012
1.32 foreach($o in $objects) { $o.Name } 0.015
9.07 $objects.ForEach({ $_.Name }) 0.105
10.30 $objects.ForEach('Name') 0.119
12.70 $objects | % { $_.Name } 0.147
27.04 $objects | % Name 0.312
29.70 $objects | Select-Object -ExpandProperty Name 0.343
Conclusions:
- In PowerShell Core,
.ForEach('Name')clearly outperforms.ForEach({ $_.Name }). In Windows PowerShell, curiously, the latter is faster, albeit only marginally so.
Timings with [pscustomobject] instances:
- PowerShell Core v7.0.0-preview.3
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.006
1.11 foreach($o in $objects) { $o.Name } 0.007
1.52 $objects.ForEach('Name') 0.009
6.11 $objects.ForEach({ $_.Name }) 0.038
9.47 $objects | Select-Object -ExpandProperty Name 0.058
10.29 $objects | % { $_.Name } 0.063
29.77 $objects | % Name 0.184
- Windows PowerShell v5.1.18362.145
Factor Command Secs (10-run avg.)
------ ------- ------------------
1.00 $objects.Name 0.008
1.14 foreach($o in $objects) { $o.Name } 0.009
1.76 $objects.ForEach('Name') 0.015
10.36 $objects | Select-Object -ExpandProperty Name 0.085
11.18 $objects.ForEach({ $_.Name }) 0.092
16.79 $objects | % { $_.Name } 0.138
61.14 $objects | % Name 0.503
Conclusions:
Note how with
[pscustomobject]input.ForEach('Name')by far outperforms the script-block based variant,.ForEach({ $_.Name }).Similarly,
[pscustomobject]input makes the pipeline-basedSelect-Object -ExpandProperty Namefaster, in Windows PowerShell virtually on par with.ForEach({ $_.Name }), but in PowerShell Core still about 50% slower.In short: With the odd exception of
% Name, with[pscustomobject]the string-based methods of referencing the properties outperform the scriptblock-based ones.
Source code for the tests:
Note:
Download function
Time-Commandfrom this Gist to run these tests.Set
$useCustomObjectInputto$trueto measure with[pscustomobject]instances instead.
$count = 1e4 # max. input object count == 10,000
$runs = 10 # number of runs to average
# Note: Using [pscustomobject] instances rather than instances of
# regular .NET types changes the performance characteristics.
# Set this to $true to test with [pscustomobject] instances below.
$useCustomObjectInput = $false
# Create sample input objects.
if ($useCustomObjectInput) {
# Use [pscustomobject] instances.
$objects = 1..$count | % { [pscustomobject] @{ Name = "$foobar_$_"; Other1 = 1; Other2 = 2; Other3 = 3; Other4 = 4 } }
} else {
# Use instances of a regular .NET type.
# Note: The actual count of files and folders in your home dir. tree
# may be less than $count
$objects = Get-ChildItem -Recurse $HOME | Select-Object -First $count
}
Write-Host "Comparing property-value extraction methods with $($objects.Count) input objects, averaged over $runs runs..."
# An array of script blocks with the various approaches.
$approaches = { $objects | Select-Object -ExpandProperty Name },
{ $objects | % Name },
{ $objects | % { $_.Name } },
{ $objects.ForEach('Name') },
{ $objects.ForEach({ $_.Name }) },
{ $objects.Name },
{ foreach($o in $objects) { $o.Name } }
# Time the approaches and sort them by execution time (fastest first):
Time-Command $approaches -Count $runs | Select Factor, Command, Secs*
来源:https://stackoverflow.com/questions/5176815/select-the-values-of-one-property-on-all-objects-of-an-array-in-powershell