0

Example of calculating a sum using Measure-Object:

PS C:\> dir C:\Windows | Measure-Object -Property Length -Sum


Count    : 28
Average  :
Sum      : 8752440
Maximum  :
Minimum  :
Property : Length

There are a few ways to pull out the actual sum value.

PS C:\> (dir C:\Windows | Measure-Object -Property Length -Sum).Sum
8752440
PS C:\> dir C:\Windows | Measure-Object -Property Length -Sum | % Sum
8752440
PS C:\> dir C:\Windows | Measure-Object -Property Length -Sum | Select-Object -ExpandProperty Sum
8752440
PS C:\>

Which is the recommended approach?

dharmatech
  • 8,979
  • 8
  • 42
  • 88
  • 2
    Since all these approaches have the same result there is no recommendation which one to use. Choose the one you like the most. Don't overthink this. I'd focus more on writing clean code and avoid aliasses instead. ;-) – Olaf May 17 '23 at 05:13
  • 2
    The question could be lass specific and brought down to **what is the difference between the [`Select--Object -ExpandProperty` parameter](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-object#-expandproperty), [member-access enumeration](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_member-access_enumeration) and manually iterate throught the properties** – iRon May 17 '23 at 06:16
  • 2
    which mainly covered here: [Select the values of one property on all objects of an array in PowerShell](https://stackoverflow.com/q/5176815/1701026) – iRon May 17 '23 at 06:16

1 Answers1

0

Realistically I don't think there's any real difference, so which ever you prefer is fine.

For some PowerShell commands you can find that one way of doing it is a lot more efficient than another, but not in this case. It tends to be more where you for instance have multiple things in a pipeline, and the different order you do them within the pipeline makes a difference to the end result.

For any command you can use Measure-Command to determine how long a given command took to complete, but when using that in this instance, eg

Measure-Command {(dir C:\Windows | Measure-Object -Property Length -Sum).Sum} | select TotalMilliSeconds
Measure-Command {dir C:\Windows | Measure-Object -Property Length -Sum | % Sum} | select TotalMilliSeconds
Measure-Command {dir C:\Windows | Measure-Object -Property Length -Sum | Select-Object -ExpandProperty Sum} | select TotalMilliSeconds

you find that you essentially get the same result... or more accurately, there is only a small difference, but it's small enough that if you run it multiple times you'll see different results each time, with perhaps the first version being fastest on one test, and then being slowest on the next test.

Keith Langmead
  • 785
  • 1
  • 5
  • 16