2

can you help me with this simple example script? How do I refer to "custom expression property" on single one "select-object"?

I would like: single "select-object"

Get-Process | Select-Object Id, 
    @{name="MyProp"; expression={$_.id}},
    @{name="MyPropRef"; expression={$_.MyProp}}

...but third property "MyPropRef" is not displayed!

   Id MyProp MyPropRef
   -- ------ ---------
 3780   3780

While with double select-object piped, "MyPropRef" is displayed

Get-Process | Select-Object Id, 
    @{name="MyProp"; expression={$_.id}} | Select-Object *,
    @{name="MyPropRef"; expression={$_.MyProp}}

   Id MyProp MyPropRef
   -- ------ ---------
 3780   3780      3780

Thanks

byrollo
  • 21
  • 3

1 Answers1

1

Calculated properties only operate on the input objects' original properties, they cannot refer to each other.

If you need to add additional properties based on previously calculated properties, you indeed need another (expensive) Select-Object call.

Your command:

Get-Process | Select-Object Id, 
    @{name="MyProp"; expression={$_.id}},
    @{name="MyPropRef"; expression={$_.MyProp}}

creates a .MyPropRef property, but its value is $null, because the System.Diagnostics.Process instances that Get-Process outputs themselves do not have a .MyPropRef property.


If you want to make do with a single Select-Object call without repetition, you can define the script blocks used in the calculated properties in variables beforehand and reuse them across calculated property definitions; e.g.:

$myPropExpr = { $_.id }
Get-Process | Select-Object Id, 
    @{ name="MyProp"; expression=$myPropExpr },
    @{ name="MyPropRef"; expression={ "!" + (& $myPropExpr) }}

This would yield something like:

Id   MyProp  MyPropRef
--   ------  ---------
3780   3780      !3780
...
mklement0
  • 382,024
  • 64
  • 607
  • 775