We help IT Professionals succeed at work.

Powershell: add noteproperty to customobject

janhoedt
janhoedt asked
on
Hi,

I have a Powershell object  Selected.System.Management.Automation.PSCustomObject
to which I would like to add a noteproperty so I can populate it with a foreach

F.e. customobject is fruits
it has noteproperties colour,weight

In another script I d like to add taste noteproperty

How can I do this?

Tried
 $Fruits | Add-Member -MemberType NoteProperty -Name Taste -Value VeryGood -Force but then it adds everywhere test wheras I just need the extra Taste.

Please advise
J.
Comment
Watch Question

Top Expert 2014

Commented:
Do you want to add the taste to every item in $Fruits?

Is there a difference between "Taste" and "extra Taste"?

Author

Commented:

Yes.

"wheras I just need the (extra) Taste."

just Taste, nothing else

Top Expert 2014

Commented:
How is your $Fruits variable defined?

Pardon the pun, but I want to avoid an apples-to-oranges solution.
Top Expert 2014
Commented:
Here's an example of adding the taste=verygood property to a list of fruit objects.

Note: Either of the two Add-Member statements will work.  I tested both.  Commented one of them before testing the other.  This may not be 100% correct, but it is a step in the right direction.
$Fruits = @()
$Fruits += [pscustomobject]@{'name'= "apple"; attribs = [pscustomobject]@{'colour'='red'; 'weight'=.25}}
$Fruits += [pscustomobject]@{'name'= "orange"; attribs = [pscustomobject]@{'colour'='orange'; 'weight'=.3}}
#$Fruits
#$Fruits | fl
#"======================="

$tasteProp = @{Taste='VeryGood'}

$Fruits = $Fruits | %{
            Add-Member -InputObject $_.attribs -NotePropertyName Taste -NotePropertyValue 'VeryGood'
            #Add-Member -InputObject $_.attribs -NotePropertyMembers $tasteProp
            $_
          }

$Fruits

Open in new window