powershellcalculated-property

Powershell Add-Member with an expression for the value


Trying to add a new member to an array of powershell objects, can't get the expression to evaluate. Here's some example code:

$testData =
@([pscustomobject]@{Name="Cat";Legs=4},
[pscustomobject]@{Name="Parrot";Legs=2},
[pscustomobject]@{Name="Snake";Legs=0})

# this works
$testData | Select-Object Name, Legs, @{N='CopyName';E={$_.Name}}

# why doesnt this work?
$testData | Add-Member -NotePropertyName "CopyName" -NotePropertyValue $_.Name
$testData

(Using Powershell 7)


Solution

  • this works:
    $testData | Select-Object Name, Legs, @{N='CopyName';E={$_.Name}}

    This works, because you're using a calculated property to define the CopyName property, and the script block ({ ... }) in your E (Expression) entry allows you to refer to the .Name property of the input object at hand via the automatic $_ variable.

    Note:

    As an aside: You don't have to explicitly enumerate the existing properties (Name, Legs): you can refer to them abstractly as *, given that wildcard expressions as property names are supported:
    $testData | Select-Object *, @{N='CopyName';E={$_.Name}}


    why doesnt this work?:
    $testData | Add-Member -NotePropertyName "CopyName" -NotePropertyValue $_.Name

    This doesn't work, because using $_ to refer to the current pipeline input object only works inside a script block.

    However, -NotePropertyValue { $_.Name } does not work either:


    Given the above, you must call Add-Member on the objects in $testData individually, such as via ForEach-Object:

    $testData |
      ForEach-Object {
        # Due to being inside the ForEach-Object script block, $_.Name
        # now refers to the current input object's .Name property.
        # Add -PassThru to also *output* the modified object.
        Add-Member -InputObject $_ -NotePropertyName "CopyName" -NotePropertyValue $_.Name
      }