PowerShell Genie

Create a calculated property

Script 2 min read Windows PowerShell 5.1 and PowerShell 7

Documentation: Microsoft Learn

Select-Object accepts a hashtable with an n key naming the new column and an e key holding a script block that computes its value.

The script

1PS> Get-Process | Select-Object Name,@{ Name = "MemoryMB"; Expression = { [math]::Round($_.WorkingSet64/1MB, 1)} }

Script reader

Inspect before you run

Inspection only

Inspect the script below. It does not run in this browser.

Inspection only — no command has run.

    Show reference output
    1 Name MemoryMB
    2 ---- --------
    3 pwsh 84.7
    4 explorer 196.3
    5 chrome 512.4
    Inspect this example’s structure

    Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.

    Get-Process | Select-Object Name,@{ Name = "MemoryMB"; Expression = { [math]::Round($_.WorkingSet64/1MB, 1)} }
    1. Stage 1Get-ProcessPositional values or no named parameters
    2. Stage 2Select-ObjectPositional values or no named parameters

      How it works

      Select-Object accepts a hashtable with an n key naming the new column and an e key holding a script block that computes its value. Inside that block $_ is the current object, so WorkingSet64 gets divided by 1MB and rounded to one decimal, appearing in the output as MemoryMB.

      Adapting it

      Those n and e keys are shorthand for Name and Expression, and spelling them out in full makes the intent obvious to whoever reads the script a year from now.

      If the result is unexpected

      A calculated property is blank, repeated or rounded unexpectedly.

      The expression may reference the wrong property, use the wrong units or capture a variable instead of the current object.

      1. Evaluate the calculation on a single known object and confirm the units and numeric type.

      Validate the result

      The calculated value agrees with a manually checked sample.

      Keep the check reliable

      Keep the unrounded numeric value for calculations and round only when the report requires it.

      Primary documentation

      Get-Process reference

      Continue
      Genie guideCreate a calculated property

      Select-Object accepts a hashtable with an n key naming the new column and an e key holding a script block that computes its value.