1

I have been watching some CBT Nuggets on PowerShell recently and in one of them the instructor says that utilizing ForEach-Object should be a last resort with using available cmdlets and WMI Methods first. So, my question is what would be the most efficient way to get a property from multiple objects of the same type? For example:

would this:

(Get-ADComputer -Filter *).Name

be more efficient than this:

Get-ADComputer -Filter * | ForEach-Object {$_.Name}

and how do these function differently from each other?

sud0
  • 537
  • 4
  • 18
  • I think the general rule is that if the cmdlet allows you to filter, you should use it. This avoids putting a bunch of stuff you don't need in the pipeline. When typing the command, push any filtering as far to the "left" as you can (i.e. prefer cmdlet built-in filtering to ForEach-Object or Select-Object) – Josh Petitt Apr 01 '14 at 02:35
  • To improve the efficiency of a process, you should look to the `whole solution` as **the performance of a complete (PowerShell) solution is supposed to be better than the sum of its parts**, see also: [Fastest Way to get a uniquely index item from the property of an array](https://stackoverflow.com/a/59437162/1701026) – iRon Mar 16 '20 at 11:15

1 Answers1

1
#This is compatible with PowerShell 3 and later only
    (Get-ADComputer -Filter *).Name

#This is the more compatible method
    Get-ADComputer -Filter * | Select-Object -ExpandProperty Name

#This technically works, but is inefficient.  Might be useful if you need to work with the other properties
    Get-ADComputer -Filter * | ForEach-Object {$_.Name}

#This breaks the pipeline, but could be slightly faster than Foreach-Object
    foreach($computer in (Get-ADComputer -Filter *) )
    {
        $computer.name
    }

I generally stick to Select-Object -ExpandProperty to ensure compatibility.

Cheers!

Cookie Monster
  • 1,741
  • 1
  • 19
  • 24